1. Project Clover database Thu Dec 20 2018 14:37:19 IST
  2. Package org.wso2.carbon.apimgt.impl.utils

File APIUtil.java

 

Coverage histogram

../../../../../../img/srcFileCovDistChart6.png
41% of files have more coverage

Code metrics

1,136
3,310
252
1
7,649
5,490
1,087
0.33
13.13
252
4.31

Classes

Class Line # Actions
APIUtil 235 3,310 0% 1,087 2,081
0.557045655.7%
 

Contributing tests

This file is covered by 465 tests. .

Source view

1    /*
2    * Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
3    *
4    * WSO2 Inc. licenses this file to you under the Apache License,
5    * Version 2.0 (the "License"); you may not use this file except
6    * in compliance with the License.
7    * You may obtain a copy of the License at
8    *
9    * http://www.apache.org/licenses/LICENSE-2.0
10    *
11    * Unless required by applicable law or agreed to in writing,
12    * software distributed under the License is distributed on an
13    * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14    * KIND, either express or implied. See the License for the
15    * specific language governing permissions and limitations
16    * under the License.
17    */
18   
19    package org.wso2.carbon.apimgt.impl.utils;
20   
21    import com.google.gson.Gson;
22    import org.apache.axiom.om.OMElement;
23    import org.apache.axiom.om.impl.builder.StAXOMBuilder;
24    import org.apache.axiom.om.util.AXIOMUtil;
25    import org.apache.axis2.AxisFault;
26    import org.apache.axis2.Constants;
27    import org.apache.axis2.client.Options;
28    import org.apache.axis2.client.ServiceClient;
29    import org.apache.axis2.context.ConfigurationContext;
30    import org.apache.axis2.description.TransportOutDescription;
31    import org.apache.axis2.engine.AxisConfiguration;
32    import org.apache.axis2.transport.http.HTTPConstants;
33    import org.apache.axis2.util.JavaUtils;
34    import org.apache.commons.codec.binary.Base64;
35    import org.apache.commons.io.FileUtils;
36    import org.apache.commons.io.IOUtils;
37    import org.apache.commons.lang.ArrayUtils;
38    import org.apache.commons.lang.StringUtils;
39    import org.apache.commons.logging.Log;
40    import org.apache.commons.logging.LogFactory;
41    import org.apache.http.HttpEntity;
42    import org.apache.http.HttpHeaders;
43    import org.apache.http.HttpResponse;
44    import org.apache.http.HttpStatus;
45    import org.apache.http.client.ClientProtocolException;
46    import org.apache.http.client.HttpClient;
47    import org.apache.http.client.methods.HttpPost;
48    import org.apache.http.conn.scheme.PlainSocketFactory;
49    import org.apache.http.conn.scheme.Scheme;
50    import org.apache.http.conn.scheme.SchemeRegistry;
51    import org.apache.http.conn.ssl.SSLSocketFactory;
52    import org.apache.http.conn.ssl.X509HostnameVerifier;
53    import org.apache.http.entity.ContentType;
54    import org.apache.http.entity.StringEntity;
55    import org.apache.http.impl.client.DefaultHttpClient;
56    import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
57    import org.apache.http.params.BasicHttpParams;
58    import org.apache.http.params.HttpParams;
59    import org.apache.http.util.EntityUtils;
60    import org.apache.solr.common.SolrDocument;
61    import org.apache.solr.common.SolrDocumentList;
62    import org.apache.xerces.util.SecurityManager;
63    import org.json.simple.JSONArray;
64    import org.json.simple.JSONObject;
65    import org.json.simple.parser.JSONParser;
66    import org.json.simple.parser.ParseException;
67    import org.w3c.dom.Document;
68    import org.wso2.carbon.CarbonConstants;
69    import org.wso2.carbon.apimgt.api.APIManagementException;
70    import org.wso2.carbon.apimgt.api.LoginPostExecutor;
71    import org.wso2.carbon.apimgt.api.NewPostLoginExecutor;
72    import org.wso2.carbon.apimgt.api.doc.model.APIDefinition;
73    import org.wso2.carbon.apimgt.api.doc.model.APIResource;
74    import org.wso2.carbon.apimgt.api.doc.model.Operation;
75    import org.wso2.carbon.apimgt.api.doc.model.Parameter;
76    import org.wso2.carbon.apimgt.api.model.API;
77    import org.wso2.carbon.apimgt.api.model.APIIdentifier;
78    import org.wso2.carbon.apimgt.api.model.APIPublisher;
79    import org.wso2.carbon.apimgt.api.model.APIStatus;
80    import org.wso2.carbon.apimgt.api.model.APIStore;
81    import org.wso2.carbon.apimgt.api.model.Application;
82    import org.wso2.carbon.apimgt.api.model.CORSConfiguration;
83    import org.wso2.carbon.apimgt.api.model.Documentation;
84    import org.wso2.carbon.apimgt.api.model.DocumentationType;
85    import org.wso2.carbon.apimgt.api.model.KeyManagerConfiguration;
86    import org.wso2.carbon.apimgt.api.model.Label;
87    import org.wso2.carbon.apimgt.api.model.Provider;
88    import org.wso2.carbon.apimgt.api.model.Scope;
89    import org.wso2.carbon.apimgt.api.model.Tier;
90    import org.wso2.carbon.apimgt.api.model.URITemplate;
91    import org.wso2.carbon.apimgt.api.model.policy.APIPolicy;
92    import org.wso2.carbon.apimgt.api.model.policy.ApplicationPolicy;
93    import org.wso2.carbon.apimgt.api.model.policy.BandwidthLimit;
94    import org.wso2.carbon.apimgt.api.model.policy.Limit;
95    import org.wso2.carbon.apimgt.api.model.policy.Policy;
96    import org.wso2.carbon.apimgt.api.model.policy.PolicyConstants;
97    import org.wso2.carbon.apimgt.api.model.policy.QuotaPolicy;
98    import org.wso2.carbon.apimgt.api.model.policy.RequestCountLimit;
99    import org.wso2.carbon.apimgt.api.model.policy.SubscriptionPolicy;
100    import org.wso2.carbon.apimgt.impl.APIConstants;
101    import org.wso2.carbon.apimgt.impl.APIMRegistryServiceImpl;
102    import org.wso2.carbon.apimgt.impl.APIManagerAnalyticsConfiguration;
103    import org.wso2.carbon.apimgt.impl.APIManagerConfiguration;
104    import org.wso2.carbon.apimgt.impl.ThrottlePolicyDeploymentManager;
105    import org.wso2.carbon.apimgt.impl.clients.ApplicationManagementServiceClient;
106    import org.wso2.carbon.apimgt.impl.clients.OAuthAdminClient;
107    import org.wso2.carbon.apimgt.impl.clients.UserInformationRecoveryClient;
108    import org.wso2.carbon.apimgt.impl.dao.ApiMgtDAO;
109    import org.wso2.carbon.apimgt.impl.dto.APIKeyValidationInfoDTO;
110    import org.wso2.carbon.apimgt.impl.dto.ConditionDto;
111    import org.wso2.carbon.apimgt.impl.dto.Environment;
112    import org.wso2.carbon.apimgt.impl.dto.ThrottleProperties;
113    import org.wso2.carbon.apimgt.impl.factory.KeyManagerHolder;
114    import org.wso2.carbon.apimgt.impl.internal.APIManagerComponent;
115    import org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder;
116    import org.wso2.carbon.apimgt.impl.template.APITemplateException;
117    import org.wso2.carbon.apimgt.impl.template.ThrottlePolicyTemplateBuilder;
118    import org.wso2.carbon.apimgt.keymgt.client.SubscriberKeyMgtClient;
119    import org.wso2.carbon.base.MultitenantConstants;
120    import org.wso2.carbon.base.ServerConfiguration;
121    import org.wso2.carbon.context.CarbonContext;
122    import org.wso2.carbon.context.PrivilegedCarbonContext;
123    import org.wso2.carbon.core.commons.stub.loggeduserinfo.ExceptionException;
124    import org.wso2.carbon.core.commons.stub.loggeduserinfo.LoggedUserInfo;
125    import org.wso2.carbon.core.commons.stub.loggeduserinfo.LoggedUserInfoAdminStub;
126    import org.wso2.carbon.core.multitenancy.utils.TenantAxisUtils;
127    import org.wso2.carbon.core.util.CryptoException;
128    import org.wso2.carbon.core.util.CryptoUtil;
129    import org.wso2.carbon.core.util.PermissionUpdateUtil;
130    import org.wso2.carbon.governance.api.common.dataobjects.GovernanceArtifact;
131    import org.wso2.carbon.governance.api.endpoints.EndpointManager;
132    import org.wso2.carbon.governance.api.endpoints.dataobjects.Endpoint;
133    import org.wso2.carbon.governance.api.exception.GovernanceException;
134    import org.wso2.carbon.governance.api.generic.GenericArtifactManager;
135    import org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact;
136    import org.wso2.carbon.governance.api.util.GovernanceConstants;
137    import org.wso2.carbon.governance.api.util.GovernanceUtils;
138    import org.wso2.carbon.governance.lcm.util.CommonUtil;
139    import org.wso2.carbon.identity.oauth.config.OAuthServerConfiguration;
140    import org.wso2.carbon.identity.user.profile.stub.UserProfileMgtServiceStub;
141    import org.wso2.carbon.identity.user.profile.stub.UserProfileMgtServiceUserProfileExceptionException;
142    import org.wso2.carbon.identity.user.profile.stub.types.UserProfileDTO;
143    import org.wso2.carbon.registry.core.ActionConstants;
144    import org.wso2.carbon.registry.core.Association;
145    import org.wso2.carbon.registry.core.Registry;
146    import org.wso2.carbon.registry.core.RegistryConstants;
147    import org.wso2.carbon.registry.core.Resource;
148    import org.wso2.carbon.registry.core.Tag;
149    import org.wso2.carbon.registry.core.config.Mount;
150    import org.wso2.carbon.registry.core.config.RegistryContext;
151    import org.wso2.carbon.registry.core.exceptions.RegistryException;
152    import org.wso2.carbon.registry.core.jdbc.realm.RegistryAuthorizationManager;
153    import org.wso2.carbon.registry.core.pagination.PaginationContext;
154    import org.wso2.carbon.registry.core.service.RegistryService;
155    import org.wso2.carbon.registry.core.service.TenantRegistryLoader;
156    import org.wso2.carbon.registry.core.session.UserRegistry;
157    import org.wso2.carbon.registry.core.utils.RegistryUtils;
158    import org.wso2.carbon.registry.indexing.indexer.IndexerException;
159    import org.wso2.carbon.registry.indexing.solr.SolrClient;
160    import org.wso2.carbon.user.api.Permission;
161    import org.wso2.carbon.user.api.RealmConfiguration;
162    import org.wso2.carbon.user.api.Tenant;
163    import org.wso2.carbon.user.api.UserStoreException;
164    import org.wso2.carbon.user.api.UserStoreManager;
165    import org.wso2.carbon.user.core.UserCoreConstants;
166    import org.wso2.carbon.user.core.UserRealm;
167    import org.wso2.carbon.user.core.config.RealmConfigXMLProcessor;
168    import org.wso2.carbon.user.core.service.RealmService;
169    import org.wso2.carbon.user.mgt.UserMgtConstants;
170    import org.wso2.carbon.utils.CarbonUtils;
171    import org.wso2.carbon.utils.ConfigurationContextService;
172    import org.wso2.carbon.utils.FileUtil;
173    import org.wso2.carbon.utils.NetworkUtils;
174    import org.wso2.carbon.utils.multitenancy.MultitenantUtils;
175    import org.xml.sax.SAXException;
176   
177    import java.io.File;
178    import java.io.FileInputStream;
179    import java.io.FilenameFilter;
180    import java.io.IOException;
181    import java.io.InputStream;
182    import java.io.UnsupportedEncodingException;
183    import java.math.BigDecimal;
184    import java.math.RoundingMode;
185    import java.net.Inet4Address;
186    import java.net.InetAddress;
187    import java.net.MalformedURLException;
188    import java.net.NetworkInterface;
189    import java.net.SocketException;
190    import java.net.URL;
191    import java.nio.charset.Charset;
192    import java.rmi.RemoteException;
193    import java.security.KeyManagementException;
194    import java.security.KeyStore;
195    import java.security.KeyStoreException;
196    import java.security.MessageDigest;
197    import java.security.NoSuchAlgorithmException;
198    import java.security.UnrecoverableKeyException;
199    import java.security.cert.CertificateException;
200    import java.util.ArrayList;
201    import java.util.Arrays;
202    import java.util.Collections;
203    import java.util.Comparator;
204    import java.util.Enumeration;
205    import java.util.HashMap;
206    import java.util.HashSet;
207    import java.util.Iterator;
208    import java.util.LinkedHashSet;
209    import java.util.List;
210    import java.util.Map;
211    import java.util.Map.Entry;
212    import java.util.Properties;
213    import java.util.Set;
214    import java.util.SortedSet;
215    import java.util.TreeMap;
216    import java.util.TreeSet;
217    import java.util.concurrent.TimeUnit;
218    import javax.cache.Cache;
219    import javax.cache.CacheConfiguration;
220    import javax.cache.CacheManager;
221    import javax.cache.Caching;
222    import javax.xml.XMLConstants;
223    import javax.xml.namespace.QName;
224    import javax.xml.parsers.DocumentBuilder;
225    import javax.xml.parsers.DocumentBuilderFactory;
226    import javax.xml.parsers.ParserConfigurationException;
227    import javax.xml.stream.XMLInputFactory;
228    import javax.xml.stream.XMLStreamException;
229    import javax.xml.stream.XMLStreamReader;
230   
231    /**
232    * This class contains the utility methods used by the implementations of APIManager, APIProvider
233    * and APIConsumer interfaces.
234    */
 
235    public final class APIUtil {
236   
237    private static final Log log = LogFactory.getLog(APIUtil.class);
238   
239    private static final Log audit = CarbonConstants.AUDIT_LOG;
240   
241    private static boolean isContextCacheInitialized = false;
242   
243    public static final String DISABLE_ROLE_VALIDATION_AT_SCOPE_CREATION = "disableRoleValidationAtScopeCreation";
244   
245    private static final int ENTITY_EXPANSION_LIMIT = 0;
246   
247    private static final String DESCRIPTION = "Allows [1] request(s) per minute.";
248   
249    private static final int DEFAULT_TENANT_IDLE_MINS = 30;
250    private static long tenantIdleTimeMillis;
251    private static Set<String> currentLoadingTenants = new HashSet<String>();
252   
253    private static volatile Set<String> whiteListedScopes;
254    private static boolean isPublisherRoleCacheEnabled = true;
255   
256    public static final String STRICT = "Strict";
257    public static final String ALLOW_ALL = "AllowAll";
258    public static final String DEFAULT_AND_LOCALHOST = "DefaultAndLocalhost";
259    public static final String HOST_NAME_VERIFIER = "httpclient.hostnameVerifier";
260    public static String multiGrpAppSharing = null;
261   
262    //Need tenantIdleTime to check whether the tenant is in idle state in loadTenantConfig method
 
263  18 toggle static {
264  18 tenantIdleTimeMillis =
265    Long.parseLong(System.getProperty(
266    org.wso2.carbon.utils.multitenancy.MultitenantConstants.TENANT_IDLE_TIME,
267    String.valueOf(DEFAULT_TENANT_IDLE_MINS)))
268    * 60 * 1000;
269    }
270   
271    private static String hostAddress = null;
272   
273    /**
274    * To initialize the publisherRoleCache configurations, based on configurations.
275    */
 
276  18 toggle public static void init() {
277  18 APIManagerConfiguration apiManagerConfiguration = ServiceReferenceHolder.getInstance()
278    .getAPIManagerConfigurationService().getAPIManagerConfiguration();
279  18 String isPublisherRoleCacheEnabledConfiguration = apiManagerConfiguration
280    .getFirstProperty(APIConstants.PUBLISHER_ROLE_CACHE_ENABLED);
281  18 isPublisherRoleCacheEnabled = isPublisherRoleCacheEnabledConfiguration == null || Boolean
282    .parseBoolean(isPublisherRoleCacheEnabledConfiguration);
283    }
284   
285    /**
286    * This method used to get API from governance artifact
287    *
288    * @param artifact API artifact
289    * @param registry Registry
290    * @return API
291    * @throws APIManagementException if failed to get API from artifact
292    */
 
293  1298 toggle public static API getAPI(GovernanceArtifact artifact, Registry registry)
294    throws APIManagementException {
295   
296  1298 API api;
297  1298 try {
298  1298 String providerName = artifact.getAttribute(APIConstants.API_OVERVIEW_PROVIDER);
299  1298 String apiName = artifact.getAttribute(APIConstants.API_OVERVIEW_NAME);
300  1298 String apiVersion = artifact.getAttribute(APIConstants.API_OVERVIEW_VERSION);
301  1298 APIIdentifier apiIdentifier = new APIIdentifier(providerName, apiName, apiVersion);
302  1298 int apiId = ApiMgtDAO.getInstance().getAPIID(apiIdentifier, null);
303   
304  1298 if (apiId == -1) {
305  0 return null;
306    }
307  1298 api = new API(apiIdentifier);
308    // set rating
309  1298 String artifactPath = GovernanceUtils.getArtifactPath(registry, artifact.getId());
310  1298 api = setResourceProperties(api, registry, artifactPath);
311  1298 api.setRating(getAverageRating(apiId));
312    //set description
313  1298 api.setDescription(artifact.getAttribute(APIConstants.API_OVERVIEW_DESCRIPTION));
314    //set last access time
315  1298 api.setLastUpdated(registry.get(artifactPath).getLastModified());
316    //set uuid
317  1298 api.setUUID(artifact.getId());
318    //setting api ID for scope retrieval
319  1298 api.getId().setApplicationId(Integer.toString(apiId));
320    // set url
321  1298 api.setStatus(getLcStateFromArtifact(artifact));
322  1298 api.setThumbnailUrl(artifact.getAttribute(APIConstants.API_OVERVIEW_THUMBNAIL_URL));
323  1298 api.setWsdlUrl(artifact.getAttribute(APIConstants.API_OVERVIEW_WSDL));
324  1298 api.setWadlUrl(artifact.getAttribute(APIConstants.API_OVERVIEW_WADL));
325  1298 api.setTechnicalOwner(artifact.getAttribute(APIConstants.API_OVERVIEW_TEC_OWNER));
326  1298 api.setTechnicalOwnerEmail(artifact.getAttribute(APIConstants.API_OVERVIEW_TEC_OWNER_EMAIL));
327  1298 api.setBusinessOwner(artifact.getAttribute(APIConstants.API_OVERVIEW_BUSS_OWNER));
328  1298 api.setBusinessOwnerEmail(artifact.getAttribute(APIConstants.API_OVERVIEW_BUSS_OWNER_EMAIL));
329  1298 api.setVisibility(artifact.getAttribute(APIConstants.API_OVERVIEW_VISIBILITY));
330  1298 api.setVisibleRoles(artifact.getAttribute(APIConstants.API_OVERVIEW_VISIBLE_ROLES));
331  1298 api.setVisibleTenants(artifact.getAttribute(APIConstants.API_OVERVIEW_VISIBLE_TENANTS));
332  1298 api.setEndpointSecured(Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_SECURED)));
333  1298 api.setEndpointAuthDigest(Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_AUTH_DIGEST)));
334  1298 api.setEndpointUTUsername(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_USERNAME));
335  1298 if (!((APIConstants.DEFAULT_MODIFIED_ENDPOINT_PASSWORD)
336    .equals(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_PASSWORD)))) {
337  1298 api.setEndpointUTPassword(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_PASSWORD));
338    } else { //If APIEndpointPasswordRegistryHandler is enabled take password from the registry hidden property
339  0 api.setEndpointUTPassword(getActualEpPswdFromHiddenProperty(api, registry));
340    }
341  1298 api.setTransports(artifact.getAttribute(APIConstants.API_OVERVIEW_TRANSPORTS));
342  1298 api.setInSequence(artifact.getAttribute(APIConstants.API_OVERVIEW_INSEQUENCE));
343  1298 api.setOutSequence(artifact.getAttribute(APIConstants.API_OVERVIEW_OUTSEQUENCE));
344  1298 api.setFaultSequence(artifact.getAttribute(APIConstants.API_OVERVIEW_FAULTSEQUENCE));
345  1298 api.setResponseCache(artifact.getAttribute(APIConstants.API_OVERVIEW_RESPONSE_CACHING));
346  1298 api.setImplementation(artifact.getAttribute(APIConstants.PROTOTYPE_OVERVIEW_IMPLEMENTATION));
347  1298 api.setProductionMaxTps(artifact.getAttribute(APIConstants.API_PRODUCTION_THROTTLE_MAXTPS));
348   
349  1298 int cacheTimeout = APIConstants.API_RESPONSE_CACHE_TIMEOUT;
350  1298 try {
351  1298 cacheTimeout = Integer.parseInt(artifact.getAttribute(APIConstants.API_OVERVIEW_CACHE_TIMEOUT));
352    } catch (NumberFormatException e) {
353    //ignore
354    }
355   
356  1298 api.setCacheTimeout(cacheTimeout);
357   
358  1298 api.setEndpointConfig(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_CONFIG));
359   
360  1298 api.setRedirectURL(artifact.getAttribute(APIConstants.API_OVERVIEW_REDIRECT_URL));
361  1298 api.setApiOwner(artifact.getAttribute(APIConstants.API_OVERVIEW_OWNER));
362  1298 api.setAdvertiseOnly(Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_ADVERTISE_ONLY)));
363   
364  1298 api.setSubscriptionAvailability(artifact.getAttribute(APIConstants.API_OVERVIEW_SUBSCRIPTION_AVAILABILITY));
365  1298 api.setSubscriptionAvailableTenants(artifact.getAttribute(APIConstants.API_OVERVIEW_SUBSCRIPTION_AVAILABLE_TENANTS));
366   
367  1298 String tenantDomainName = MultitenantUtils.getTenantDomain(replaceEmailDomainBack(providerName));
368  1298 int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager()
369    .getTenantId(tenantDomainName);
370   
371  1298 boolean isGlobalThrottlingEnabled = APIUtil.isAdvanceThrottlingEnabled();
372   
373   
374  1298 if (isGlobalThrottlingEnabled) {
375  1250 String apiLevelTier = ApiMgtDAO.getInstance().getAPILevelTier(apiId);
376  1250 api.setApiLevelPolicy(apiLevelTier);
377    }
378   
379  1298 String tiers = artifact.getAttribute(APIConstants.API_OVERVIEW_TIER);
380  1298 Map<String, Tier> definedTiers = getTiers(tenantId);
381  1298 Set<Tier> availableTier = getAvailableTiers(definedTiers, tiers, apiName);
382  1298 api.addAvailableTiers(availableTier);
383  1298 api.setMonetizationCategory(getAPIMonetizationCategory(availableTier, tenantDomainName));
384   
385   
386  1298 api.setContext(artifact.getAttribute(APIConstants.API_OVERVIEW_CONTEXT));
387    // We set the context template here
388  1298 api.setContextTemplate(artifact.getAttribute(APIConstants.API_OVERVIEW_CONTEXT_TEMPLATE));
389  1298 api.setLatest(Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_IS_LATEST)));
390   
391   
392  1298 Set<URITemplate> uriTemplates = new LinkedHashSet<URITemplate>();
393  1298 List<String> uriTemplateNames = new ArrayList<String>();
394   
395  1298 Set<Scope> scopes = ApiMgtDAO.getInstance().getAPIScopes(api.getId());
396  1298 api.setScopes(scopes);
397   
398  1298 HashMap<String, String> urlPatternsSet;
399  1298 urlPatternsSet = ApiMgtDAO.getInstance().getURITemplatesPerAPIAsString(api.getId());
400   
401  1298 HashMap<String, String> resourceScopesMap;
402  1298 resourceScopesMap = ApiMgtDAO.getInstance().getResourceToScopeMapping(api.getId());
403   
404  1298 Set<String> urlPatternsKeySet = urlPatternsSet.keySet();
405  1298 String resourceScopeKey;
406  1298 for (String urlPattern : urlPatternsKeySet) {
407  2083 URITemplate uriTemplate = new URITemplate();
408  2083 String[] urlPatternComponents = urlPattern.split("::");
409  2083 String uTemplate = (urlPatternComponents.length >= 1) ? urlPatternComponents[0] : null;
410  2083 String method = (urlPatternComponents.length >= 2) ? urlPatternComponents[1] : null;
411  2083 String authType = (urlPatternComponents.length >= 3) ? urlPatternComponents[2] : null;
412  2083 String throttlingTier = (urlPatternComponents.length >= 4) ? urlPatternComponents[3] : null;
413  2083 String mediationScript = (urlPatternComponents.length >= 5) ? urlPatternComponents[4] : null;
414  2083 uriTemplate.setHTTPVerb(method);
415  2083 uriTemplate.setAuthType(authType);
416  2083 uriTemplate.setThrottlingTier(throttlingTier);
417  2083 uriTemplate.setHttpVerbs(method);
418  2083 uriTemplate.setAuthTypes(authType);
419  2083 uriTemplate.setUriTemplate(uTemplate);
420  2083 uriTemplate.setResourceURI(api.getUrl());
421  2083 uriTemplate.setResourceSandboxURI(api.getSandboxUrl());
422  2083 uriTemplate.setThrottlingTiers(throttlingTier);
423  2083 uriTemplate.setMediationScript(mediationScript);
424  2083 resourceScopeKey = APIUtil.getResourceKey(api.getContext(), apiVersion, uTemplate, method);
425  2083 uriTemplate.setScopes(findScopeByKey(scopes, resourceScopesMap.get(resourceScopeKey)));
426    //Checking for duplicate uri template names
427  2083 if (uriTemplateNames.contains(uTemplate)) {
428  719 for (URITemplate tmp : uriTemplates) {
429  719 if (uTemplate.equals(tmp.getUriTemplate())) {
430  719 tmp.setHttpVerbs(method);
431  719 tmp.setAuthTypes(authType);
432  719 tmp.setThrottlingTiers(throttlingTier);
433  719 resourceScopeKey = APIUtil.getResourceKey(api.getContext(), apiVersion, uTemplate, method);
434  719 tmp.setScopes(findScopeByKey(scopes, resourceScopesMap.get(resourceScopeKey)));
435  719 break;
436    }
437    }
438    } else {
439  1364 uriTemplates.add(uriTemplate);
440    }
441  2083 uriTemplateNames.add(uTemplate);
442    }
443  1298 api.setUriTemplates(uriTemplates);
444  1298 api.setAsDefaultVersion(Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_IS_DEFAULT_VERSION)));
445  1298 Set<String> tags = new HashSet<String>();
446  1298 Tag[] tag = registry.getTags(artifactPath);
447  1298 for (Tag tag1 : tag) {
448  2392 tags.add(tag1.getTagName());
449    }
450  1298 api.addTags(tags);
451  1298 api.setLastUpdated(registry.get(artifactPath).getLastModified());
452  1298 api.setImplementation(artifact.getAttribute(APIConstants.PROTOTYPE_OVERVIEW_IMPLEMENTATION));
453  1298 String environments = artifact.getAttribute(APIConstants.API_OVERVIEW_ENVIRONMENTS);
454  1298 api.setEnvironments(extractEnvironmentsForAPI(environments));
455  1298 api.setCorsConfiguration(getCorsConfigurationFromArtifact(artifact));
456  1298 api.setAuthorizationHeader(artifact.getAttribute(APIConstants.API_OVERVIEW_AUTHORIZATION_HEADER));
457  1298 api.setApiSecurity(artifact.getAttribute(APIConstants.API_OVERVIEW_API_SECURITY));
458   
459    } catch (GovernanceException e) {
460  0 String msg = "Failed to get API for artifact ";
461  0 throw new APIManagementException(msg, e);
462    } catch (RegistryException e) {
463  0 String msg = "Failed to get LastAccess time or Rating";
464  0 throw new APIManagementException(msg, e);
465    } catch (UserStoreException e) {
466  0 String msg = "Failed to get User Realm of API Provider";
467  0 throw new APIManagementException(msg, e);
468    }
469  1298 return api;
470    }
471   
472    /**
473    * This Method is different from getAPI method, as this one returns
474    * URLTemplates without aggregating duplicates. This is to be used for building synapse config.
475    *
476    * @param artifact
477    * @param registry
478    * @return API
479    * @throws org.wso2.carbon.apimgt.api.APIManagementException
480    */
 
481  1582 toggle public static API getAPIForPublishing(GovernanceArtifact artifact, Registry registry)
482    throws APIManagementException {
483   
484  1582 API api;
485  1582 try {
486  1582 String providerName = artifact.getAttribute(APIConstants.API_OVERVIEW_PROVIDER);
487  1582 String apiName = artifact.getAttribute(APIConstants.API_OVERVIEW_NAME);
488  1582 String apiVersion = artifact.getAttribute(APIConstants.API_OVERVIEW_VERSION);
489  1582 APIIdentifier apiIdentifier = new APIIdentifier(providerName, apiName, apiVersion);
490  1582 int apiId = ApiMgtDAO.getInstance().getAPIID(apiIdentifier, null);
491   
492  1582 if (apiId == -1) {
493  0 return null;
494    }
495   
496  1582 api = new API(apiIdentifier);
497    //set uuid
498  1582 api.setUUID(artifact.getId());
499    // set rating
500  1582 String artifactPath = GovernanceUtils.getArtifactPath(registry, artifact.getId());
501  1582 api = setResourceProperties(api, registry, artifactPath);
502  1582 api.setRating(getAverageRating(apiId));
503    //set description
504  1582 api.setDescription(artifact.getAttribute(APIConstants.API_OVERVIEW_DESCRIPTION));
505    //set last access time
506  1582 api.setLastUpdated(registry.get(artifactPath).getLastModified());
507    // set url
508  1582 api.setStatus(getLcStateFromArtifact(artifact));
509  1582 api.setThumbnailUrl(artifact.getAttribute(APIConstants.API_OVERVIEW_THUMBNAIL_URL));
510  1582 api.setWsdlUrl(artifact.getAttribute(APIConstants.API_OVERVIEW_WSDL));
511  1582 api.setWadlUrl(artifact.getAttribute(APIConstants.API_OVERVIEW_WADL));
512  1582 api.setTechnicalOwner(artifact.getAttribute(APIConstants.API_OVERVIEW_TEC_OWNER));
513  1582 api.setTechnicalOwnerEmail(artifact.getAttribute(APIConstants.API_OVERVIEW_TEC_OWNER_EMAIL));
514  1582 api.setBusinessOwner(artifact.getAttribute(APIConstants.API_OVERVIEW_BUSS_OWNER));
515  1582 api.setBusinessOwnerEmail(artifact.getAttribute(APIConstants.API_OVERVIEW_BUSS_OWNER_EMAIL));
516  1582 api.setVisibility(artifact.getAttribute(APIConstants.API_OVERVIEW_VISIBILITY));
517  1582 api.setVisibleRoles(artifact.getAttribute(APIConstants.API_OVERVIEW_VISIBLE_ROLES));
518  1582 api.setVisibleTenants(artifact.getAttribute(APIConstants.API_OVERVIEW_VISIBLE_TENANTS));
519  1582 api.setEndpointSecured(Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_SECURED)));
520  1582 api.setEndpointAuthDigest(Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_AUTH_DIGEST)));
521  1582 api.setEndpointUTUsername(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_USERNAME));
522  1582 if (!((APIConstants.DEFAULT_MODIFIED_ENDPOINT_PASSWORD)
523    .equals(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_PASSWORD)))) {
524  1582 api.setEndpointUTPassword(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_PASSWORD));
525    } else { //If APIEndpointPasswordRegistryHandler is enabled take password from the registry hidden property
526  0 api.setEndpointUTPassword(getActualEpPswdFromHiddenProperty(api, registry));
527    }
528  1582 api.setTransports(artifact.getAttribute(APIConstants.API_OVERVIEW_TRANSPORTS));
529  1582 api.setInSequence(artifact.getAttribute(APIConstants.API_OVERVIEW_INSEQUENCE));
530  1582 api.setOutSequence(artifact.getAttribute(APIConstants.API_OVERVIEW_OUTSEQUENCE));
531  1582 api.setFaultSequence(artifact.getAttribute(APIConstants.API_OVERVIEW_FAULTSEQUENCE));
532  1582 api.setResponseCache(artifact.getAttribute(APIConstants.API_OVERVIEW_RESPONSE_CACHING));
533  1582 api.setImplementation(artifact.getAttribute(APIConstants.PROTOTYPE_OVERVIEW_IMPLEMENTATION));
534  1582 api.setType(artifact.getAttribute(APIConstants.API_OVERVIEW_TYPE));
535  1582 api.setProductionMaxTps(artifact.getAttribute(APIConstants.API_PRODUCTION_THROTTLE_MAXTPS));
536  1582 api.setSandboxMaxTps(artifact.getAttribute(APIConstants.API_SANDBOX_THROTTLE_MAXTPS));
537   
538  1582 int cacheTimeout = APIConstants.API_RESPONSE_CACHE_TIMEOUT;
539  1582 try {
540  1582 String strCacheTimeout = artifact.getAttribute(APIConstants.API_OVERVIEW_CACHE_TIMEOUT);
541  1582 if (strCacheTimeout != null && !strCacheTimeout.isEmpty()) {
542  1582 cacheTimeout = Integer.parseInt(strCacheTimeout);
543    }
544    } catch (NumberFormatException e) {
545  0 if (log.isWarnEnabled()) {
546  0 log.warn("Error while retrieving cache timeout from the registry for " + apiIdentifier);
547    }
548    // ignore the exception and use default cache timeout value
549    }
550   
551  1582 api.setCacheTimeout(cacheTimeout);
552   
553  1582 api.setEndpointConfig(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_CONFIG));
554   
555  1582 api.setRedirectURL(artifact.getAttribute(APIConstants.API_OVERVIEW_REDIRECT_URL));
556  1582 api.setApiOwner(artifact.getAttribute(APIConstants.API_OVERVIEW_OWNER));
557  1582 api.setAdvertiseOnly(Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_ADVERTISE_ONLY)));
558  1582 api.setType(artifact.getAttribute(APIConstants.API_OVERVIEW_TYPE));
559  1582 api.setSubscriptionAvailability(artifact.getAttribute(APIConstants.API_OVERVIEW_SUBSCRIPTION_AVAILABILITY));
560  1582 api.setSubscriptionAvailableTenants(artifact.getAttribute(APIConstants.API_OVERVIEW_SUBSCRIPTION_AVAILABLE_TENANTS));
561   
562  1582 String tenantDomainName = MultitenantUtils.getTenantDomain(replaceEmailDomainBack(providerName));
563  1582 int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager()
564    .getTenantId(tenantDomainName);
565   
566  1582 APIManagerConfiguration config = ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService()
567    .getAPIManagerConfiguration();
568  1582 boolean isGlobalThrottlingEnabled = APIUtil.isAdvanceThrottlingEnabled();
569   
570  1582 if (isGlobalThrottlingEnabled) {
571  1513 String apiLevelTier = ApiMgtDAO.getInstance().getAPILevelTier(apiId);
572  1513 api.setApiLevelPolicy(apiLevelTier);
573    }
574   
575  1582 String tiers = artifact.getAttribute(APIConstants.API_OVERVIEW_TIER);
576  1582 Map<String, Tier> definedTiers = getTiers(tenantId);
577  1582 Set<Tier> availableTier = getAvailableTiers(definedTiers, tiers, apiName);
578  1582 api.addAvailableTiers(availableTier);
579   
580    // This contains the resolved context
581  1582 api.setContext(artifact.getAttribute(APIConstants.API_OVERVIEW_CONTEXT));
582    // We set the context template here
583  1582 api.setContextTemplate(artifact.getAttribute(APIConstants.API_OVERVIEW_CONTEXT_TEMPLATE));
584  1582 api.setLatest(Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_IS_LATEST)));
585   
586   
587  1582 Set<URITemplate> uriTemplates = new LinkedHashSet<URITemplate>();
588  1582 List<String> uriTemplateNames = new ArrayList<String>();
589   
590  1582 Set<Scope> scopes = ApiMgtDAO.getInstance().getAPIScopes(api.getId());
591  1582 api.setScopes(scopes);
592   
593  1582 HashMap<String, String> urlPatternsSet;
594  1582 urlPatternsSet = ApiMgtDAO.getInstance().getURITemplatesPerAPIAsString(api.getId());
595  1582 HashMap<String, String> resourceScopes;
596  1582 resourceScopes = ApiMgtDAO.getInstance().getResourceToScopeMapping(api.getId());
597   
598  1582 Set<String> urlPatternsKeySet = urlPatternsSet.keySet();
599  1582 String resourceScopeKey;
600  1582 for (String urlPattern : urlPatternsKeySet) {
601  2617 URITemplate uriTemplate = new URITemplate();
602  2617 String[] urlPatternComponents = urlPattern.split("::");
603  2617 String uTemplate = (urlPatternComponents.length >= 1) ? urlPatternComponents[0] : null;
604  2617 String method = (urlPatternComponents.length >= 2) ? urlPatternComponents[1] : null;
605  2617 String authType = (urlPatternComponents.length >= 3) ? urlPatternComponents[2] : null;
606  2617 String throttlingTier = (urlPatternComponents.length >= 4) ? urlPatternComponents[3] : null;
607  2617 String mediationScript = (urlPatternComponents.length >= 5) ? urlPatternComponents[4] : null;
608  2617 uriTemplate.setHTTPVerb(method);
609  2617 uriTemplate.setAuthType(authType);
610  2617 uriTemplate.setThrottlingTier(throttlingTier);
611  2617 uriTemplate.setHttpVerbs(method);
612  2617 uriTemplate.setAuthTypes(authType);
613  2617 uriTemplate.setUriTemplate(uTemplate);
614  2617 uriTemplate.setResourceURI(api.getUrl());
615  2617 uriTemplate.setResourceSandboxURI(api.getSandboxUrl());
616  2617 uriTemplate.setThrottlingTiers(throttlingTier);
617  2617 uriTemplate.setMediationScript(mediationScript);
618  2617 uriTemplate.setMediationScripts(method, mediationScript);
619  2617 resourceScopeKey = APIUtil.getResourceKey(api.getContext(), apiVersion, uTemplate, method);
620  2617 uriTemplate.setScopes(findScopeByKey(scopes, resourceScopes.get(resourceScopeKey)));
621    //Checking for duplicate uri template names
622   
623  2617 if (uriTemplateNames.contains(uTemplate)) {
624  897 for (URITemplate tmp : uriTemplates) {
625  897 if (uTemplate.equals(tmp.getUriTemplate())) {
626  897 tmp.setHttpVerbs(method);
627  897 tmp.setAuthTypes(authType);
628  897 tmp.setThrottlingTiers(throttlingTier);
629  897 tmp.setMediationScripts(method, mediationScript);
630  897 resourceScopeKey = APIUtil.getResourceKey(api.getContext(), apiVersion, uTemplate, method);
631  897 tmp.setScopes(findScopeByKey(scopes, resourceScopes.get(resourceScopeKey)));
632  897 break;
633    }
634    }
635    } else {
636  1720 uriTemplates.add(uriTemplate);
637    }
638  2617 uriTemplateNames.add(uTemplate);
639    }
640   
641  1582 if (APIConstants.IMPLEMENTATION_TYPE_INLINE.equalsIgnoreCase(api.getImplementation())) {
642  0 for (URITemplate template : uriTemplates) {
643  0 template.setMediationScript(template.getAggregatedMediationScript());
644    }
645    }
646   
647  1582 api.setUriTemplates(uriTemplates);
648  1582 api.setAsDefaultVersion(Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_IS_DEFAULT_VERSION)));
649  1582 Set<String> tags = new HashSet<String>();
650  1582 Tag[] tag = registry.getTags(artifactPath);
651  1582 for (Tag tag1 : tag) {
652  3094 tags.add(tag1.getTagName());
653    }
654  1582 api.addTags(tags);
655  1582 api.setLastUpdated(registry.get(artifactPath).getLastModified());
656  1582 api.setCreatedTime(String.valueOf(registry.get(artifactPath).getCreatedTime().getTime()));
657  1582 api.setImplementation(artifact.getAttribute(APIConstants.PROTOTYPE_OVERVIEW_IMPLEMENTATION));
658  1582 String environments = artifact.getAttribute(APIConstants.API_OVERVIEW_ENVIRONMENTS);
659  1582 api.setEnvironments(extractEnvironmentsForAPI(environments));
660  1582 api.setCorsConfiguration(getCorsConfigurationFromArtifact(artifact));
661  1582 api.setAuthorizationHeader(artifact.getAttribute(APIConstants.API_OVERVIEW_AUTHORIZATION_HEADER));
662  1582 api.setApiSecurity(artifact.getAttribute(APIConstants.API_OVERVIEW_API_SECURITY));
663    //get labels from the artifact and set to API object
664  1582 String[] labelArray = artifact.getAttributes(APIConstants.API_LABELS_GATEWAY_LABELS);
665  1582 if (labelArray != null && labelArray.length > 0) {
666  0 String tenantDomain = MultitenantUtils.getTenantDomain
667    (replaceEmailDomainBack(api.getId().getProviderName()));
668  0 List<Label> allLabelList = APIUtil.getAllLabels(tenantDomain);
669  0 List<Label> gatewayLabelListForAPI = new ArrayList<>();
670  0 for (String labelName : labelArray) {
671  0 Label label = new Label();
672    //set the name
673  0 label.setName(labelName);
674    //set the description and access URLs
675  0 for (Label currentLabel : allLabelList) {
676  0 if (labelName.equalsIgnoreCase(currentLabel.getName())) {
677  0 label.setDescription(currentLabel.getDescription());
678  0 label.setAccessUrls(currentLabel.getAccessUrls());
679    }
680    }
681  0 gatewayLabelListForAPI.add(label);
682    }
683  0 api.setGatewayLabels(gatewayLabelListForAPI);
684    }
685   
686    //get endpoint config string from artifact, parse it as a json and set the environment list configured with
687    //non empty URLs to API object
688  1582 try {
689  1582 api.setEnvironmentList(extractEnvironmentListForAPI(
690    artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_CONFIG)));
691    } catch (ParseException e) {
692  0 String msg = "Failed to parse endpoint config JSON of API: " + apiName + " " + apiVersion;
693  0 log.error(msg, e);
694  0 throw new APIManagementException(msg, e);
695    } catch (ClassCastException e) {
696  0 String msg = "Invalid endpoint config JSON found in API: " + apiName + " " + apiVersion;
697  0 log.error(msg, e);
698  0 throw new APIManagementException(msg, e);
699    }
700   
701    } catch (GovernanceException e) {
702  0 String msg = "Failed to get API for artifact ";
703  0 throw new APIManagementException(msg, e);
704    } catch (RegistryException e) {
705  0 String msg = "Failed to get LastAccess time or Rating";
706  0 throw new APIManagementException(msg, e);
707    } catch (UserStoreException e) {
708  0 String msg = "Failed to get User Realm of API Provider";
709  0 throw new APIManagementException(msg, e);
710    }
711  1582 return api;
712    }
713   
714    /**
715    * This method used to extract environment list configured with non empty URLs.
716    *
717    * @param endpointConfigs (Eg: {"production_endpoints":{"url":"http://www.test.com/v1/xxx","config":null,
718    * "template_not_supported":false},"endpoint_type":"http"})
719    * @return Set<String>
720    */
 
721  2199 toggle private static Set<String> extractEnvironmentListForAPI(String endpointConfigs)
722    throws ParseException, ClassCastException {
723  2199 Set<String> environmentList = new HashSet<String>();
724  2199 if (endpointConfigs != null) {
725  2189 JSONParser parser = new JSONParser();
726  2189 JSONObject endpointConfigJson = (JSONObject) parser.parse(endpointConfigs);
727  2189 if (endpointConfigJson.containsKey(APIConstants.API_DATA_PRODUCTION_ENDPOINTS) &&
728    isEndpointURLNonEmpty(endpointConfigJson.get(APIConstants.API_DATA_PRODUCTION_ENDPOINTS))) {
729  2189 environmentList.add(APIConstants.API_KEY_TYPE_PRODUCTION);
730    }
731  2189 if (endpointConfigJson.containsKey(APIConstants.API_DATA_SANDBOX_ENDPOINTS) &&
732    isEndpointURLNonEmpty(endpointConfigJson.get(APIConstants.API_DATA_SANDBOX_ENDPOINTS))) {
733  165 environmentList.add(APIConstants.API_KEY_TYPE_SANDBOX);
734    }
735    }
736  2199 return environmentList;
737    }
738   
739    /**
740    * This method used to check whether the endpoints JSON object has a non empty URL.
741    *
742    * @param endpoints (Eg: {"url":"http://www.test.com/v1/xxx","config":null,"template_not_supported":false})
743    * @return boolean
744    */
 
745  2397 toggle private static boolean isEndpointURLNonEmpty(Object endpoints) {
746  2397 if (endpoints instanceof JSONObject) {
747  2354 JSONObject endpointJson = (JSONObject) endpoints;
748  2354 if (endpointJson.containsKey(APIConstants.API_DATA_URL) &&
749    endpointJson.get(APIConstants.API_DATA_URL) != null) {
750  2354 String url = (endpointJson.get(APIConstants.API_DATA_URL)).toString();
751  2354 if (StringUtils.isNotBlank(url)) {
752  2354 return true;
753    }
754    }
755  43 } else if (endpoints instanceof JSONArray) {
756  43 JSONArray endpointsJson = (JSONArray) endpoints;
757  43 for (int i = 0; i < endpointsJson.size(); i++) {
758  43 if (isEndpointURLNonEmpty(endpointsJson.get(i))) {
759  43 return true;
760    }
761    }
762    }
763  0 return false;
764    }
765   
 
766  617 toggle public static API getAPI(GovernanceArtifact artifact)
767    throws APIManagementException {
768   
769  617 API api;
770  617 try {
771  617 String providerName = artifact.getAttribute(APIConstants.API_OVERVIEW_PROVIDER);
772  617 String apiName = artifact.getAttribute(APIConstants.API_OVERVIEW_NAME);
773  617 String apiVersion = artifact.getAttribute(APIConstants.API_OVERVIEW_VERSION);
774  617 APIIdentifier apiIdentifier = new APIIdentifier(providerName, apiName, apiVersion);
775  617 api = new API(apiIdentifier);
776  617 int apiId = ApiMgtDAO.getInstance().getAPIID(apiIdentifier, null);
777  617 if (apiId == -1) {
778  0 return null;
779    }
780    //set uuid
781  617 api.setUUID(artifact.getId());
782  617 api.setRating(getAverageRating(apiId));
783  617 api.setThumbnailUrl(artifact.getAttribute(APIConstants.API_OVERVIEW_THUMBNAIL_URL));
784  617 api.setStatus(getLcStateFromArtifact(artifact));
785  617 api.setContext(artifact.getAttribute(APIConstants.API_OVERVIEW_CONTEXT));
786  617 api.setVisibility(artifact.getAttribute(APIConstants.API_OVERVIEW_VISIBILITY));
787  617 api.setVisibleRoles(artifact.getAttribute(APIConstants.API_OVERVIEW_VISIBLE_ROLES));
788  617 api.setVisibleTenants(artifact.getAttribute(APIConstants.API_OVERVIEW_VISIBLE_TENANTS));
789  617 api.setTransports(artifact.getAttribute(APIConstants.API_OVERVIEW_TRANSPORTS));
790  617 api.setInSequence(artifact.getAttribute(APIConstants.API_OVERVIEW_INSEQUENCE));
791  617 api.setOutSequence(artifact.getAttribute(APIConstants.API_OVERVIEW_OUTSEQUENCE));
792  617 api.setFaultSequence(artifact.getAttribute(APIConstants.API_OVERVIEW_FAULTSEQUENCE));
793  617 api.setDescription(artifact.getAttribute(APIConstants.API_OVERVIEW_DESCRIPTION));
794  617 api.setResponseCache(artifact.getAttribute(APIConstants.API_OVERVIEW_RESPONSE_CACHING));
795  617 api.setType(artifact.getAttribute(APIConstants.API_OVERVIEW_TYPE));
796  617 int cacheTimeout = APIConstants.API_RESPONSE_CACHE_TIMEOUT;
797  617 try {
798  617 cacheTimeout = Integer.parseInt(artifact.getAttribute(APIConstants.API_OVERVIEW_CACHE_TIMEOUT));
799    } catch (NumberFormatException e) {
800    //ignore
801    }
802  617 api.setCacheTimeout(cacheTimeout);
803   
804  617 boolean isGlobalThrottlingEnabled = APIUtil.isAdvanceThrottlingEnabled();
805   
806  617 if (isGlobalThrottlingEnabled) {
807  607 String apiLevelTier = ApiMgtDAO.getInstance().getAPILevelTier(apiId);
808  607 api.setApiLevelPolicy(apiLevelTier);
809   
810  607 Set<Tier> availablePolicy = new HashSet<Tier>();
811  607 String[] subscriptionPolicy = ApiMgtDAO.getInstance().getPolicyNames(PolicyConstants.POLICY_LEVEL_SUB, replaceEmailDomainBack(providerName));
812  607 List<String> definedPolicyNames = Arrays.asList(subscriptionPolicy);
813  607 String policies = artifact.getAttribute(APIConstants.API_OVERVIEW_TIER);
814  607 if (policies != null && !"".equals(policies)) {
815  600 String[] policyNames = policies.split("\\|\\|");
816  600 for (String policyName : policyNames) {
817  793 if (definedPolicyNames.contains(policyName) || APIConstants.UNLIMITED_TIER.equals(policyName)) {
818  793 Tier p = new Tier(policyName);
819  793 availablePolicy.add(p);
820    } else {
821  0 log.warn("Unknown policy: " + policyName + " found on API: " + apiName);
822    }
823    }
824    }
825   
826  607 api.addAvailableTiers(availablePolicy);
827  607 String tenantDomainName = MultitenantUtils.getTenantDomain(replaceEmailDomainBack(providerName));
828  607 api.setMonetizationCategory(getAPIMonetizationCategory(availablePolicy, tenantDomainName));
829    } else {
830    //deprecated throttling method
831  10 Set<Tier> availableTier = new HashSet<Tier>();
832  10 String tiers = artifact.getAttribute(APIConstants.API_OVERVIEW_TIER);
833  10 String tenantDomainName = MultitenantUtils.getTenantDomain(replaceEmailDomainBack(providerName));
834  10 if (tiers != null) {
835  10 String[] tierNames = tiers.split("\\|\\|");
836  10 for (String tierName : tierNames) {
837  10 Tier tier = new Tier(tierName);
838  10 availableTier.add(tier);
839   
840    }
841   
842  10 api.addAvailableTiers(availableTier);
843  10 api.setMonetizationCategory(getAPIMonetizationCategory(availableTier, tenantDomainName));
844    } else {
845  0 api.setMonetizationCategory(getAPIMonetizationCategory(availableTier, tenantDomainName));
846    }
847    }
848   
849  617 api.setRedirectURL(artifact.getAttribute(APIConstants.API_OVERVIEW_REDIRECT_URL));
850  617 api.setApiOwner(artifact.getAttribute(APIConstants.API_OVERVIEW_OWNER));
851  617 api.setAdvertiseOnly(Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_ADVERTISE_ONLY)));
852   
853  617 api.setEndpointConfig(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_CONFIG));
854   
855  617 api.setSubscriptionAvailability(artifact.getAttribute(APIConstants.API_OVERVIEW_SUBSCRIPTION_AVAILABILITY));
856  617 api.setSubscriptionAvailableTenants(artifact.getAttribute(APIConstants.API_OVERVIEW_SUBSCRIPTION_AVAILABLE_TENANTS));
857   
858  617 api.setAsDefaultVersion(Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_IS_DEFAULT_VERSION)));
859  617 api.setImplementation(artifact.getAttribute(APIConstants.PROTOTYPE_OVERVIEW_IMPLEMENTATION));
860  617 api.setTechnicalOwner(artifact.getAttribute(APIConstants.API_OVERVIEW_TEC_OWNER));
861  617 api.setTechnicalOwnerEmail(artifact.getAttribute(APIConstants.API_OVERVIEW_TEC_OWNER_EMAIL));
862  617 api.setBusinessOwner(artifact.getAttribute(APIConstants.API_OVERVIEW_BUSS_OWNER));
863  617 api.setBusinessOwnerEmail(artifact.getAttribute(APIConstants.API_OVERVIEW_BUSS_OWNER_EMAIL));
864   
865  617 ArrayList<URITemplate> urlPatternsList;
866  617 urlPatternsList = ApiMgtDAO.getInstance().getAllURITemplates(api.getContext(), api.getId().getVersion());
867  617 Set<URITemplate> uriTemplates = new HashSet<URITemplate>(urlPatternsList);
868   
869  617 for (URITemplate uriTemplate : uriTemplates) {
870  891 uriTemplate.setResourceURI(api.getUrl());
871  891 uriTemplate.setResourceSandboxURI(api.getSandboxUrl());
872   
873    }
874  617 api.setUriTemplates(uriTemplates);
875  617 String environments = artifact.getAttribute(APIConstants.API_OVERVIEW_ENVIRONMENTS);
876  617 api.setEnvironments(extractEnvironmentsForAPI(environments));
877  617 api.setCorsConfiguration(getCorsConfigurationFromArtifact(artifact));
878  617 api.setAuthorizationHeader(artifact.getAttribute(APIConstants.API_OVERVIEW_AUTHORIZATION_HEADER));
879  617 api.setApiSecurity(artifact.getAttribute(APIConstants.API_OVERVIEW_API_SECURITY));
880   
881    //get endpoint config string from artifact, parse it as a json and set the environment list configured with
882    //non empty URLs to API object
883  617 try {
884  617 api.setEnvironmentList(extractEnvironmentListForAPI(
885    artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_CONFIG)));
886    } catch (ParseException e) {
887  0 String msg = "Failed to parse endpoint config JSON of API: " + apiName + " " + apiVersion;
888  0 log.error(msg, e);
889  0 throw new APIManagementException(msg, e);
890    } catch (ClassCastException e) {
891  0 String msg = "Invalid endpoint config JSON found in API: " + apiName + " " + apiVersion;
892  0 log.error(msg, e);
893  0 throw new APIManagementException(msg, e);
894    }
895    } catch (GovernanceException e) {
896  0 String msg = "Failed to get API from artifact ";
897  0 throw new APIManagementException(msg, e);
898    }
899  617 return api;
900    }
901   
902    /**
903    * This method used to get Provider from provider artifact
904    *
905    * @param artifact provider artifact
906    * @return Provider
907    * @throws APIManagementException if failed to get Provider from provider artifact.
908    */
 
909  0 toggle public static Provider getProvider(GenericArtifact artifact) throws APIManagementException {
910  0 Provider provider;
911  0 try {
912  0 provider = new Provider(artifact.getAttribute(APIConstants.PROVIDER_OVERVIEW_NAME));
913  0 provider.setDescription(artifact.getAttribute(APIConstants.PROVIDER_OVERVIEW_DESCRIPTION));
914  0 provider.setEmail(artifact.getAttribute(APIConstants.PROVIDER_OVERVIEW_EMAIL));
915   
916    } catch (GovernanceException e) {
917  0 String msg = "Failed to get provider ";
918  0 log.error(msg, e);
919  0 throw new APIManagementException(msg, e);
920    }
921  0 return provider;
922    }
923   
924    /**
925    * Returns a list of scopes when passed the Provider Name and Scope Key
926    *
927    * @param scopeKey
928    * @param provider
929    * @return
930    * @throws APIManagementException
931    */
 
932  0 toggle public static Set<Scope> getScopeByScopeKey(String scopeKey, String provider) throws APIManagementException {
933  0 Set<Scope> scopeSet = null;
934  0 String tenantDomainName = MultitenantUtils.getTenantDomain(replaceEmailDomainBack(provider));
935  0 try {
936  0 int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager()
937    .getTenantId(tenantDomainName);
938  0 scopeSet = ApiMgtDAO.getInstance().getAPIScopesByScopeKey(scopeKey, tenantId);
939    } catch (UserStoreException e) {
940  0 String msg = "Error while retrieving Scopes";
941  0 log.error(msg, e);
942  0 handleException(msg);
943    }
944  0 return scopeSet;
945    }
946   
947    /**
948    * Create Governance artifact from given attributes
949    *
950    * @param artifact initial governance artifact
951    * @param api API object with the attributes value
952    * @return GenericArtifact
953    * @throws org.wso2.carbon.apimgt.api.APIManagementException if failed to create API
954    */
 
955  571 toggle public static GenericArtifact createAPIArtifactContent(GenericArtifact artifact, API api)
956    throws APIManagementException {
957  571 try {
958  571 String apiStatus = api.getStatus();
959  571 artifact.setAttribute(APIConstants.API_OVERVIEW_NAME, api.getId().getApiName());
960  571 artifact.setAttribute(APIConstants.API_OVERVIEW_VERSION, api.getId().getVersion());
961   
962  571 artifact.setAttribute(APIConstants.API_OVERVIEW_IS_DEFAULT_VERSION, String.valueOf(api.isDefaultVersion()));
963   
964  571 artifact.setAttribute(APIConstants.API_OVERVIEW_CONTEXT, api.getContext());
965  571 artifact.setAttribute(APIConstants.API_OVERVIEW_PROVIDER, api.getId().getProviderName());
966  571 artifact.setAttribute(APIConstants.API_OVERVIEW_DESCRIPTION, api.getDescription());
967  571 artifact.setAttribute(APIConstants.API_OVERVIEW_WSDL, api.getWsdlUrl());
968  571 artifact.setAttribute(APIConstants.API_OVERVIEW_WADL, api.getWadlUrl());
969  571 artifact.setAttribute(APIConstants.API_OVERVIEW_THUMBNAIL_URL, api.getThumbnailUrl());
970  571 artifact.setAttribute(APIConstants.API_OVERVIEW_STATUS, apiStatus);
971  571 artifact.setAttribute(APIConstants.API_OVERVIEW_TEC_OWNER, api.getTechnicalOwner());
972  571 artifact.setAttribute(APIConstants.API_OVERVIEW_TEC_OWNER_EMAIL, api.getTechnicalOwnerEmail());
973  571 artifact.setAttribute(APIConstants.API_OVERVIEW_BUSS_OWNER, api.getBusinessOwner());
974  571 artifact.setAttribute(APIConstants.API_OVERVIEW_BUSS_OWNER_EMAIL, api.getBusinessOwnerEmail());
975  571 artifact.setAttribute(APIConstants.API_OVERVIEW_VISIBILITY, api.getVisibility());
976  571 artifact.setAttribute(APIConstants.API_OVERVIEW_VISIBLE_ROLES, api.getVisibleRoles());
977  571 artifact.setAttribute(APIConstants.API_OVERVIEW_VISIBLE_TENANTS, api.getVisibleTenants());
978  571 artifact.setAttribute(APIConstants.API_OVERVIEW_ENDPOINT_SECURED, Boolean.toString(api.isEndpointSecured()));
979  571 artifact.setAttribute(APIConstants.API_OVERVIEW_ENDPOINT_AUTH_DIGEST, Boolean.toString(api.isEndpointAuthDigest()));
980  571 artifact.setAttribute(APIConstants.API_OVERVIEW_ENDPOINT_USERNAME, api.getEndpointUTUsername());
981  571 artifact.setAttribute(APIConstants.API_OVERVIEW_ENDPOINT_PASSWORD, api.getEndpointUTPassword());
982  571 artifact.setAttribute(APIConstants.API_OVERVIEW_TRANSPORTS, api.getTransports());
983  571 artifact.setAttribute(APIConstants.API_OVERVIEW_INSEQUENCE, api.getInSequence());
984  571 artifact.setAttribute(APIConstants.API_OVERVIEW_OUTSEQUENCE, api.getOutSequence());
985  571 artifact.setAttribute(APIConstants.API_OVERVIEW_FAULTSEQUENCE, api.getFaultSequence());
986  571 artifact.setAttribute(APIConstants.API_OVERVIEW_RESPONSE_CACHING, api.getResponseCache());
987  571 artifact.setAttribute(APIConstants.API_OVERVIEW_CACHE_TIMEOUT, Integer.toString(api.getCacheTimeout()));
988   
989  571 artifact.setAttribute(APIConstants.API_OVERVIEW_REDIRECT_URL, api.getRedirectURL());
990  571 artifact.setAttribute(APIConstants.API_OVERVIEW_OWNER, api.getApiOwner());
991  571 artifact.setAttribute(APIConstants.API_OVERVIEW_ADVERTISE_ONLY, Boolean.toString(api.isAdvertiseOnly()));
992   
993  571 artifact.setAttribute(APIConstants.API_OVERVIEW_ENDPOINT_CONFIG, api.getEndpointConfig());
994   
995  571 artifact.setAttribute(APIConstants.API_OVERVIEW_SUBSCRIPTION_AVAILABILITY, api.getSubscriptionAvailability());
996  571 artifact.setAttribute(APIConstants.API_OVERVIEW_SUBSCRIPTION_AVAILABLE_TENANTS, api.getSubscriptionAvailableTenants());
997   
998  571 artifact.setAttribute(APIConstants.PROTOTYPE_OVERVIEW_IMPLEMENTATION, api.getImplementation());
999   
1000  571 artifact.setAttribute(APIConstants.API_PRODUCTION_THROTTLE_MAXTPS, api.getProductionMaxTps());
1001  571 artifact.setAttribute(APIConstants.API_SANDBOX_THROTTLE_MAXTPS, api.getSandboxMaxTps());
1002  571 artifact.setAttribute(APIConstants.API_OVERVIEW_AUTHORIZATION_HEADER, api.getAuthorizationHeader());
1003  571 artifact.setAttribute(APIConstants.API_OVERVIEW_API_SECURITY, api.getApiSecurity());
1004   
1005    //Validate if the API has an unsupported context before setting it in the artifact
1006  571 String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain();
1007  571 if (APIConstants.SUPER_TENANT_DOMAIN.equals(tenantDomain)) {
1008  422 String invalidContext = File.separator + APIConstants.VERSION_PLACEHOLDER;
1009  422 if (invalidContext.equals(api.getContextTemplate())) {
1010  0 throw new APIManagementException(
1011    "API : " + api.getId() + " has an unsupported context : " + api.getContextTemplate());
1012    }
1013    } else {
1014  149 String invalidContext =
1015    APIConstants.TENANT_PREFIX + tenantDomain + File.separator + APIConstants.VERSION_PLACEHOLDER;
1016  149 if (invalidContext.equals(api.getContextTemplate())) {
1017  0 throw new APIManagementException(
1018    "API : " + api.getId() + " has an unsupported context : " + api.getContextTemplate());
1019    }
1020    }
1021    // This is to support the pluggable version strategy.
1022  571 artifact.setAttribute(APIConstants.API_OVERVIEW_CONTEXT_TEMPLATE, api.getContextTemplate());
1023  571 artifact.setAttribute(APIConstants.API_OVERVIEW_VERSION_TYPE, "context");
1024  571 artifact.setAttribute(APIConstants.API_OVERVIEW_TYPE, api.getType());
1025   
1026  571 StringBuilder policyBuilder = new StringBuilder();
1027  571 for (Tier tier : api.getAvailableTiers()) {
1028  714 policyBuilder.append(tier.getName());
1029  714 policyBuilder.append("||");
1030    }
1031   
1032  571 String policies = policyBuilder.toString();
1033   
1034  571 if (!"".equals(policies)) {
1035  561 policies = policies.substring(0, policies.length() - 2);
1036  561 artifact.setAttribute(APIConstants.API_OVERVIEW_TIER, policies);
1037    }
1038   
1039  571 StringBuilder tiersBuilder = new StringBuilder();
1040  571 for (Tier tier : api.getAvailableTiers()) {
1041  714 tiersBuilder.append(tier.getName());
1042  714 tiersBuilder.append("||");
1043    }
1044   
1045  571 String tiers = tiersBuilder.toString();
1046   
1047  571 if (!"".equals(tiers)) {
1048  561 tiers = tiers.substring(0, tiers.length() - 2);
1049  561 artifact.setAttribute(APIConstants.API_OVERVIEW_TIER, tiers);
1050    }
1051   
1052  571 if (APIConstants.PUBLISHED.equals(apiStatus)) {
1053  271 artifact.setAttribute(APIConstants.API_OVERVIEW_IS_LATEST, "true");
1054    }
1055  571 String[] keys = artifact.getAttributeKeys();
1056  571 for (String key : keys) {
1057  26371 if (key.contains("URITemplate")) {
1058  1473 artifact.removeAttribute(key);
1059    }
1060    }
1061   
1062  571 Set<URITemplate> uriTemplateSet = api.getUriTemplates();
1063  571 int i = 0;
1064  571 for (URITemplate uriTemplate : uriTemplateSet) {
1065  817 artifact.addAttribute(APIConstants.API_URI_PATTERN + i, uriTemplate.getUriTemplate());
1066  817 artifact.addAttribute(APIConstants.API_URI_HTTP_METHOD + i, uriTemplate.getHTTPVerb());
1067  817 artifact.addAttribute(APIConstants.API_URI_AUTH_TYPE + i, uriTemplate.getAuthType());
1068   
1069  817 i++;
1070   
1071    }
1072  571 artifact.setAttribute(APIConstants.API_OVERVIEW_ENVIRONMENTS, writeEnvironmentsToArtifact(api));
1073   
1074  571 artifact.setAttribute(APIConstants.API_OVERVIEW_CORS_CONFIGURATION,
1075    APIUtil.getCorsConfigurationJsonFromDto(api.getCorsConfiguration()));
1076   
1077    //attaching micro-gateway labels to the API
1078  571 attachLabelsToAPIArtifact(artifact, api, tenantDomain);
1079   
1080  571 String apiSecurity = artifact.getAttribute(APIConstants.API_OVERVIEW_API_SECURITY);
1081  571 if (apiSecurity != null && !apiSecurity.contains(APIConstants.DEFAULT_API_SECURITY_OAUTH2)) {
1082  2 artifact.setAttribute(APIConstants.API_OVERVIEW_TIER, "");
1083    }
1084    } catch (GovernanceException e) {
1085  0 String msg = "Failed to create API for : " + api.getId().getApiName();
1086  0 log.error(msg, e);
1087  0 throw new APIManagementException(msg, e);
1088    }
1089  571 return artifact;
1090    }
1091   
1092    /**
1093    * This method is used to attach micro-gateway labels to the given API
1094    *
1095    * @param artifact genereic artifact
1096    * @param api API
1097    * @param tenantDomain domain name of the tenant
1098    * @throws APIManagementException if failed to attach micro-gateway labels
1099    */
 
1100  822 toggle public static void attachLabelsToAPIArtifact(GenericArtifact artifact, API api, String tenantDomain)
1101    throws APIManagementException {
1102   
1103    //get all labels in the tenant
1104  822 List<Label> gatewayLabelList = APIUtil.getAllLabels(tenantDomain);
1105    //validation is performed here to cover all actions related to API artifact updates
1106  822 if (!gatewayLabelList.isEmpty()) {
1107    //put available gateway labels to a list for validation purpose
1108  0 List<String> availableGatewayLabelListNames = new ArrayList<>();
1109  0 for (Label x : gatewayLabelList) {
1110  0 availableGatewayLabelListNames.add(x.getName());
1111    }
1112  0 try {
1113    //clear all the existing labels first
1114  0 artifact.removeAttribute(APIConstants.API_LABELS_GATEWAY_LABELS);
1115    //if there are labels attached to the API object, add them to the artifact
1116  0 if (api.getGatewayLabels() != null) {
1117    //validate and add each label to the artifact
1118  0 List<Label> candidateLabelsList = api.getGatewayLabels();
1119  0 for (Label label : candidateLabelsList) {
1120  0 String candidateLabel = label.getName();
1121    //validation step, add the label only if it exists in the available gateway labels
1122  0 if (availableGatewayLabelListNames.contains(candidateLabel)) {
1123  0 artifact.addAttribute(APIConstants.API_LABELS_GATEWAY_LABELS, candidateLabel);
1124    } else {
1125  0 log.warn("Label name : " + candidateLabel + " does not exist in the tenant : " +
1126    tenantDomain + ", hence skipping it.");
1127    }
1128    }
1129    }
1130    } catch (GovernanceException e) {
1131  0 String msg = "Failed to add labels for API : " + api.getId().getApiName();
1132  0 log.error(msg, e);
1133  0 throw new APIManagementException(msg, e);
1134    }
1135    } else {
1136  822 if (log.isDebugEnabled()) {
1137  36 log.debug("No predefined labels in the tenant : " + tenantDomain + " . Skipped adding all labels");
1138    }
1139    }
1140    }
1141   
1142    /**
1143    * Create the Documentation from artifact
1144    *
1145    * @param artifact Documentation artifact
1146    * @return Documentation
1147    * @throws APIManagementException if failed to create Documentation from artifact
1148    */
 
1149  9 toggle public static Documentation getDocumentation(GenericArtifact artifact) throws APIManagementException {
1150   
1151  9 Documentation documentation;
1152   
1153  9 try {
1154  9 DocumentationType type;
1155  9 String docType = artifact.getAttribute(APIConstants.DOC_TYPE);
1156   
1157  9 if (docType.equalsIgnoreCase(DocumentationType.HOWTO.getType())) {
1158  8 type = DocumentationType.HOWTO;
1159  1 } else if (docType.equalsIgnoreCase(DocumentationType.PUBLIC_FORUM.getType())) {
1160  0 type = DocumentationType.PUBLIC_FORUM;
1161  1 } else if (docType.equalsIgnoreCase(DocumentationType.SUPPORT_FORUM.getType())) {
1162  0 type = DocumentationType.SUPPORT_FORUM;
1163  1 } else if (docType.equalsIgnoreCase(DocumentationType.API_MESSAGE_FORMAT.getType())) {
1164  0 type = DocumentationType.API_MESSAGE_FORMAT;
1165  1 } else if (docType.equalsIgnoreCase(DocumentationType.SAMPLES.getType())) {
1166  0 type = DocumentationType.SAMPLES;
1167    } else {
1168  1 type = DocumentationType.OTHER;
1169    }
1170  9 documentation = new Documentation(type, artifact.getAttribute(APIConstants.DOC_NAME));
1171  9 documentation.setId(artifact.getId());
1172  9 documentation.setSummary(artifact.getAttribute(APIConstants.DOC_SUMMARY));
1173  9 String visibilityAttr = artifact.getAttribute(APIConstants.DOC_VISIBILITY);
1174  9 Documentation.DocumentVisibility documentVisibility = Documentation.DocumentVisibility.API_LEVEL;
1175   
1176  9 if (visibilityAttr != null) {
1177  9 if (visibilityAttr.equals(Documentation.DocumentVisibility.API_LEVEL.name())) {
1178  9 documentVisibility = Documentation.DocumentVisibility.API_LEVEL;
1179  0 } else if (visibilityAttr.equals(Documentation.DocumentVisibility.PRIVATE.name())) {
1180  0 documentVisibility = Documentation.DocumentVisibility.PRIVATE;
1181  0 } else if (visibilityAttr.equals(Documentation.DocumentVisibility.OWNER_ONLY.name())) {
1182  0 documentVisibility = Documentation.DocumentVisibility.OWNER_ONLY;
1183    }
1184    }
1185  9 documentation.setVisibility(documentVisibility);
1186   
1187  9 Documentation.DocumentSourceType docSourceType = Documentation.DocumentSourceType.INLINE;
1188  9 String artifactAttribute = artifact.getAttribute(APIConstants.DOC_SOURCE_TYPE);
1189   
1190  9 if (Documentation.DocumentSourceType.URL.name().equals(artifactAttribute)) {
1191  2 docSourceType = Documentation.DocumentSourceType.URL;
1192  2 documentation.setSourceUrl(artifact.getAttribute(APIConstants.DOC_SOURCE_URL));
1193  7 } else if (Documentation.DocumentSourceType.FILE.name().equals(artifactAttribute)) {
1194  0 docSourceType = Documentation.DocumentSourceType.FILE;
1195  0 documentation.setFilePath(prependWebContextRoot(artifact.getAttribute(APIConstants.DOC_FILE_PATH)));
1196    }
1197  9 documentation.setSourceType(docSourceType);
1198  9 if (documentation.getType() == DocumentationType.OTHER) {
1199  1 documentation.setOtherTypeName(artifact.getAttribute(APIConstants.DOC_OTHER_TYPE_NAME));
1200    }
1201   
1202    } catch (GovernanceException e) {
1203  0 throw new APIManagementException("Failed to get documentation from artifact", e);
1204    }
1205  9 return documentation;
1206    }
1207   
1208    /**
1209    * Create the Documentation from artifact
1210    *
1211    * @param artifact Documentation artifact
1212    * @return Documentation
1213    * @throws APIManagementException if failed to create Documentation from artifact
1214    */
 
1215  4 toggle public static Documentation getDocumentation(GenericArtifact artifact, String docCreatorName)
1216    throws APIManagementException {
1217   
1218  4 Documentation documentation;
1219   
1220  4 try {
1221  4 DocumentationType type;
1222  4 String docType = artifact.getAttribute(APIConstants.DOC_TYPE);
1223   
1224  4 if (docType.equalsIgnoreCase(DocumentationType.HOWTO.getType())) {
1225  4 type = DocumentationType.HOWTO;
1226  0 } else if (docType.equalsIgnoreCase(DocumentationType.PUBLIC_FORUM.getType())) {
1227  0 type = DocumentationType.PUBLIC_FORUM;
1228  0 } else if (docType.equalsIgnoreCase(DocumentationType.SUPPORT_FORUM.getType())) {
1229  0 type = DocumentationType.SUPPORT_FORUM;
1230  0 } else if (docType.equalsIgnoreCase(DocumentationType.API_MESSAGE_FORMAT.getType())) {
1231  0 type = DocumentationType.API_MESSAGE_FORMAT;
1232  0 } else if (docType.equalsIgnoreCase(DocumentationType.SAMPLES.getType())) {
1233  0 type = DocumentationType.SAMPLES;
1234    } else {
1235  0 type = DocumentationType.OTHER;
1236    }
1237  4 documentation = new Documentation(type, artifact.getAttribute(APIConstants.DOC_NAME));
1238  4 documentation.setId(artifact.getId());
1239  4 documentation.setSummary(artifact.getAttribute(APIConstants.DOC_SUMMARY));
1240   
1241  4 Documentation.DocumentSourceType docSourceType = Documentation.DocumentSourceType.INLINE;
1242  4 String artifactAttribute = artifact.getAttribute(APIConstants.DOC_SOURCE_TYPE);
1243   
1244  4 if (artifactAttribute.equals(Documentation.DocumentSourceType.URL.name())) {
1245  2 docSourceType = Documentation.DocumentSourceType.URL;
1246  2 } else if (artifactAttribute.equals(Documentation.DocumentSourceType.FILE.name())) {
1247  0 docSourceType = Documentation.DocumentSourceType.FILE;
1248    }
1249   
1250  4 documentation.setSourceType(docSourceType);
1251  4 if ("URL".equals(artifact.getAttribute(APIConstants.DOC_SOURCE_TYPE))) {
1252  2 documentation.setSourceUrl(artifact.getAttribute(APIConstants.DOC_SOURCE_URL));
1253    }
1254   
1255  4 if (docSourceType == Documentation.DocumentSourceType.FILE) {
1256  0 String filePath = prependTenantPrefix(artifact.getAttribute(APIConstants.DOC_FILE_PATH), docCreatorName);
1257  0 documentation.setFilePath(prependWebContextRoot(filePath));
1258    }
1259   
1260  4 if (documentation.getType() == DocumentationType.OTHER) {
1261  0 documentation.setOtherTypeName(artifact.getAttribute(APIConstants.DOC_OTHER_TYPE_NAME));
1262    }
1263   
1264    } catch (GovernanceException e) {
1265  0 throw new APIManagementException("Failed to get documentation from artifact", e);
1266    }
1267  4 return documentation;
1268    }
1269   
 
1270  0 toggle public static APIStatus getApiStatus(String status) throws APIManagementException {
1271  0 APIStatus apiStatus = null;
1272  0 for (APIStatus aStatus : APIStatus.values()) {
1273  0 if (aStatus.getStatus().equalsIgnoreCase(status)) {
1274  0 apiStatus = aStatus;
1275    }
1276    }
1277  0 return apiStatus;
1278    }
1279   
 
1280  5001 toggle public static String getLcStateFromArtifact(GovernanceArtifact artifact) throws GovernanceException {
1281  5001 String state = (artifact.getLifecycleState() != null) ?
1282    artifact.getLifecycleState() :
1283    artifact.getAttribute(APIConstants.API_OVERVIEW_STATUS);
1284  5001 return (state != null) ? state.toUpperCase() : null;
1285    }
1286   
1287   
1288    /**
1289    * Prepends the Tenant Prefix to a registry path. ex: /t/test1.com
1290    *
1291    * @param postfixUrl path to be prepended.
1292    * @return Path prepended with he Tenant domain prefix.
1293    */
 
1294  0 toggle public static String prependTenantPrefix(String postfixUrl, String username) {
1295  0 String tenantDomain = MultitenantUtils.getTenantDomain(replaceEmailDomainBack(username));
1296  0 if (!(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain))) {
1297  0 String tenantPrefix = "/t/";
1298  0 postfixUrl = tenantPrefix + tenantDomain + postfixUrl;
1299    }
1300   
1301  0 return postfixUrl;
1302    }
1303   
1304    /**
1305    * Prepends the webcontextroot to a registry path.
1306    *
1307    * @param postfixUrl path to be prepended.
1308    * @return Path prepended with he WebContext root.
1309    */
 
1310  63 toggle public static String prependWebContextRoot(String postfixUrl) {
1311  63 String webContext = CarbonUtils.getServerConfiguration().getFirstProperty("WebContextRoot");
1312  63 if (webContext != null && !"/".equals(webContext)) {
1313  0 postfixUrl = webContext + postfixUrl;
1314    }
1315  63 return postfixUrl;
1316    }
1317   
1318    /**
1319    * Utility method for creating storage path for an icon.
1320    *
1321    * @param identifier APIIdentifier
1322    * @return Icon storage path.
1323    */
 
1324  259 toggle public static String getIconPath(APIIdentifier identifier) {
1325  259 String artifactPath = APIConstants.API_IMAGE_LOCATION + RegistryConstants.PATH_SEPARATOR +
1326    identifier.getProviderName() + RegistryConstants.PATH_SEPARATOR +
1327    identifier.getApiName() + RegistryConstants.PATH_SEPARATOR + identifier.getVersion();
1328  259 return artifactPath + RegistryConstants.PATH_SEPARATOR + APIConstants.API_ICON_IMAGE;
1329    }
1330   
1331    /**
1332    * Utility method to generate the path for a file.
1333    *
1334    * @param identifier APIIdentifier
1335    * @return Generated path.
1336    * @fileName File name.
1337    */
 
1338  10 toggle public static String getDocumentationFilePath(APIIdentifier identifier, String fileName) {
1339  10 return APIUtil.getAPIDocPath(identifier) + APIConstants.DOCUMENT_FILE_DIR +
1340    RegistryConstants.PATH_SEPARATOR + fileName;
1341    }
1342   
 
1343  403 toggle public static String getOpenAPIDefinitionFilePath(String apiName, String apiVersion, String apiProvider) {
1344  403 return APIConstants.API_ROOT_LOCATION + RegistryConstants.PATH_SEPARATOR + apiProvider + RegistryConstants.PATH_SEPARATOR +
1345    apiName + RegistryConstants.PATH_SEPARATOR + apiVersion + RegistryConstants.PATH_SEPARATOR;
1346    }
1347   
 
1348  19 toggle public static String getWSDLDefinitionFilePath(String apiName, String apiVersion, String apiProvider) {
1349  19 return APIConstants.API_WSDL_RESOURCE_LOCATION + apiProvider + "--" + apiName + apiVersion + ".wsdl";
1350    }
1351   
1352    /**
1353    * Utility method to get api path from APIIdentifier
1354    *
1355    * @param identifier APIIdentifier
1356    * @return API path
1357    */
 
1358  8513 toggle public static String getAPIPath(APIIdentifier identifier) {
1359  8513 return APIConstants.API_ROOT_LOCATION + RegistryConstants.PATH_SEPARATOR +
1360    identifier.getProviderName() + RegistryConstants.PATH_SEPARATOR +
1361    identifier.getApiName() + RegistryConstants.PATH_SEPARATOR +
1362    identifier.getVersion() + APIConstants.API_RESOURCE_NAME;
1363    }
1364   
1365    /**
1366    * Utility method to get api identifier from api path.
1367    *
1368    * @param apiPath Path of the API in registry
1369    * @return relevant API Identifier
1370    */
 
1371  10 toggle public static APIIdentifier getAPIIdentifier(String apiPath) {
1372  10 int length = (APIConstants.API_ROOT_LOCATION + RegistryConstants.PATH_SEPARATOR).length();
1373  10 if (!apiPath.contains(APIConstants.API_ROOT_LOCATION + RegistryConstants.PATH_SEPARATOR)) {
1374  0 length = (APIConstants.API_IMAGE_LOCATION + RegistryConstants.PATH_SEPARATOR).length();
1375    }
1376  10 if (length <= 0) {
1377  0 length = (APIConstants.API_DOC_LOCATION + RegistryConstants.PATH_SEPARATOR).length();
1378    }
1379  10 String relativePath = apiPath.substring(length);
1380  10 String[] values = relativePath.split(RegistryConstants.PATH_SEPARATOR);
1381  10 if (values.length > 3) {
1382  10 return new APIIdentifier(values[0], values[1], values[2]);
1383    }
1384  0 return null;
1385    }
1386   
1387    /**
1388    * Utility method to get API provider path
1389    *
1390    * @param identifier APIIdentifier
1391    * @return API provider path
1392    */
 
1393  270 toggle public static String getAPIProviderPath(APIIdentifier identifier) {
1394  270 return APIConstants.API_LOCATION + RegistryConstants.PATH_SEPARATOR + identifier.getProviderName();
1395    }
1396   
1397    /**
1398    * Utility method to get documentation path
1399    *
1400    * @param apiId APIIdentifier
1401    * @return Doc path
1402    */
 
1403  72 toggle public static String getAPIDocPath(APIIdentifier apiId) {
1404  72 return APIConstants.API_LOCATION + RegistryConstants.PATH_SEPARATOR +
1405    apiId.getProviderName() + RegistryConstants.PATH_SEPARATOR +
1406    apiId.getApiName() + RegistryConstants.PATH_SEPARATOR +
1407    apiId.getVersion() + RegistryConstants.PATH_SEPARATOR +
1408    APIConstants.DOC_DIR + RegistryConstants.PATH_SEPARATOR;
1409    }
1410   
1411    /**
1412    * Utility method to get documentation content file path
1413    *
1414    * @param apiId APIIdentifier
1415    * @param documentationName String
1416    * @return Doc content path
1417    */
 
1418  4 toggle public static String getAPIDocContentPath(APIIdentifier apiId, String documentationName) {
1419  4 return getAPIDocPath(apiId) + RegistryConstants.PATH_SEPARATOR + documentationName;
1420    }
1421   
1422    /**
1423    * This utility method used to create documentation artifact content
1424    *
1425    * @param artifact GovernanceArtifact
1426    * @param apiId APIIdentifier
1427    * @param documentation Documentation
1428    * @return GenericArtifact
1429    * @throws APIManagementException if failed to get GovernanceArtifact from Documentation
1430    */
 
1431  30 toggle public static GenericArtifact createDocArtifactContent(GenericArtifact artifact, APIIdentifier apiId,
1432    Documentation documentation) throws APIManagementException {
1433  30 try {
1434  30 artifact.setAttribute(APIConstants.DOC_NAME, documentation.getName());
1435  30 artifact.setAttribute(APIConstants.DOC_SUMMARY, documentation.getSummary());
1436  30 artifact.setAttribute(APIConstants.DOC_TYPE, documentation.getType().getType());
1437  30 artifact.setAttribute(APIConstants.DOC_VISIBILITY, documentation.getVisibility().name());
1438   
1439  30 Documentation.DocumentSourceType sourceType = documentation.getSourceType();
1440   
1441  30 switch (sourceType) {
1442  10 case INLINE:
1443  10 sourceType = Documentation.DocumentSourceType.INLINE;
1444  10 break;
1445  10 case URL:
1446  10 sourceType = Documentation.DocumentSourceType.URL;
1447  10 break;
1448  10 case FILE: {
1449  10 sourceType = Documentation.DocumentSourceType.FILE;
1450    }
1451  10 break;
1452  0 default:
1453  0 throw new APIManagementException("Unknown sourceType " + sourceType + " provided for documentation");
1454    }
1455    //Documentation Source URL is a required field in the documentation.rxt for migrated setups
1456    //Therefore setting a default value if it is not set.
1457  30 if (documentation.getSourceUrl() == null) {
1458  20 documentation.setSourceUrl(" ");
1459    }
1460  30 artifact.setAttribute(APIConstants.DOC_SOURCE_TYPE, sourceType.name());
1461  30 artifact.setAttribute(APIConstants.DOC_SOURCE_URL, documentation.getSourceUrl());
1462  30 artifact.setAttribute(APIConstants.DOC_FILE_PATH, documentation.getFilePath());
1463  30 artifact.setAttribute(APIConstants.DOC_OTHER_TYPE_NAME, documentation.getOtherTypeName());
1464  30 String basePath = apiId.getProviderName() + RegistryConstants.PATH_SEPARATOR +
1465    apiId.getApiName() + RegistryConstants.PATH_SEPARATOR + apiId.getVersion();
1466  30 artifact.setAttribute(APIConstants.DOC_API_BASE_PATH, basePath);
1467    } catch (GovernanceException e) {
1468  0 String msg = "Failed to create doc artifact content from :" + documentation.getName();
1469  0 log.error(msg, e);
1470  0 throw new APIManagementException(msg, e);
1471    }
1472  30 return artifact;
1473    }
1474   
1475    /**
1476    * this method used to initialized the ArtifactManager
1477    *
1478    * @param registry Registry
1479    * @param key , key name of the key
1480    * @return GenericArtifactManager
1481    * @throws APIManagementException if failed to initialized GenericArtifactManager
1482    */
 
1483  3751 toggle public static GenericArtifactManager getArtifactManager(Registry registry, String key) throws APIManagementException {
1484  3751 GenericArtifactManager artifactManager = null;
1485   
1486  3751 try {
1487  3751 GovernanceUtils.loadGovernanceArtifacts((UserRegistry) registry);
1488  3751 if (GovernanceUtils.findGovernanceArtifactConfiguration(key, registry) != null) {
1489  3751 artifactManager = new GenericArtifactManager(registry, key);
1490    } else {
1491  0 log.warn("Couldn't find GovernanceArtifactConfiguration of RXT: " + key +
1492    ". Tenant id set in registry : " + ((UserRegistry) registry).getTenantId() +
1493    ", Tenant domain set in PrivilegedCarbonContext: " +
1494    PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId());
1495    }
1496    } catch (RegistryException e) {
1497  0 String msg = "Failed to initialize GenericArtifactManager";
1498  0 log.error(msg, e);
1499  0 throw new APIManagementException(msg, e);
1500    }
1501  3751 return artifactManager;
1502    }
1503   
 
1504  0 toggle public static void handleException(String msg) throws APIManagementException {
1505  0 log.error(msg);
1506  0 throw new APIManagementException(msg);
1507    }
1508   
 
1509  0 toggle public static void handleException(String msg, Throwable t) throws APIManagementException {
1510  0 log.error(msg, t);
1511  0 throw new APIManagementException(msg, t);
1512    }
1513   
 
1514  0 toggle public static SubscriberKeyMgtClient getKeyManagementClient() throws APIManagementException {
1515   
1516  0 KeyManagerConfiguration configuration = KeyManagerHolder.getKeyManagerInstance().getKeyManagerConfiguration();
1517  0 String serverURL = configuration.getParameter(APIConstants.AUTHSERVER_URL);
1518  0 String username = configuration.getParameter(APIConstants.KEY_MANAGER_USERNAME);
1519  0 String password = configuration.getParameter(APIConstants.KEY_MANAGER_PASSWORD);
1520   
1521  0 if (serverURL == null) {
1522  0 handleException("API key manager URL unspecified");
1523    }
1524   
1525  0 if (username == null || password == null) {
1526  0 handleException("Authentication credentials for API key manager unspecified");
1527    }
1528   
1529  0 try {
1530  0 return new SubscriberKeyMgtClient(serverURL, username, password);
1531    } catch (Exception e) {
1532  0 handleException("Error while initializing the subscriber key management client", e);
1533  0 return null;
1534    }
1535    }
1536   
 
1537  0 toggle public static OAuthAdminClient getOauthAdminClient() throws APIManagementException {
1538   
1539  0 try {
1540  0 return new OAuthAdminClient();
1541    } catch (Exception e) {
1542  0 handleException("Error while initializing the OAuth admin client", e);
1543  0 return null;
1544    }
1545    }
1546   
 
1547  0 toggle public static UserInformationRecoveryClient getUserInformationRecoveryClient() throws APIManagementException {
1548   
1549  0 try {
1550  0 return new UserInformationRecoveryClient();
1551    } catch (Exception e) {
1552  0 handleException("Error while initializing the User information recovery client", e);
1553  0 return null;
1554    }
1555    }
1556   
1557   
 
1558  0 toggle public static ApplicationManagementServiceClient getApplicationManagementServiceClient() throws APIManagementException {
1559  0 try {
1560  0 return new ApplicationManagementServiceClient();
1561    } catch (Exception e) {
1562  0 handleException("Error while initializing the Application Management Service client", e);
1563  0 return null;
1564    }
1565    }
1566   
1567   
1568    /**
1569    * Crate an WSDL from given wsdl url. Reset the endpoint details to gateway node
1570    * *
1571    *
1572    * @param registry - Governance Registry space to save the WSDL
1573    * @param api -API instance
1574    * @return Path of the created resource
1575    * @throws APIManagementException If an error occurs while adding the WSDL
1576    */
1577   
 
1578  2 toggle public static String createWSDL(Registry registry, API api) throws RegistryException, APIManagementException {
1579   
1580  2 try {
1581  2 String wsdlResourcePath = APIConstants.API_WSDL_RESOURCE_LOCATION + api.getId().getProviderName() +
1582    "--" + api.getId().getApiName() + api.getId().getVersion() + ".wsdl";
1583   
1584  2 String absoluteWSDLResourcePath =
1585    RegistryUtils.getAbsolutePath(RegistryContext.getBaseInstance(),
1586    RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH) + wsdlResourcePath;
1587   
1588  2 APIMWSDLReader wsdlReader = new APIMWSDLReader(api.getWsdlUrl());
1589  2 OMElement wsdlContentEle;
1590  2 String wsdRegistryPath;
1591   
1592  2 String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain();
1593  2 if (org.wso2.carbon.utils.multitenancy.MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equalsIgnoreCase
1594    (tenantDomain)) {
1595  1 wsdRegistryPath = RegistryConstants.PATH_SEPARATOR + "registry"
1596    + RegistryConstants.PATH_SEPARATOR + "resource"
1597    + absoluteWSDLResourcePath;
1598    } else {
1599  1 wsdRegistryPath = "/t/" + tenantDomain + RegistryConstants.PATH_SEPARATOR + "registry"
1600    + RegistryConstants.PATH_SEPARATOR + "resource"
1601    + absoluteWSDLResourcePath;
1602    }
1603   
1604  2 Resource wsdlResource = registry.newResource();
1605    // isWSDL2Document(api.getWsdlUrl()) method only understands http or file system urls.
1606    // Hence if this is a registry url, should not go in to the following if block
1607  2 if (!api.getWsdlUrl().matches(wsdRegistryPath) && (api.getWsdlUrl().startsWith("http:") || api.getWsdlUrl
1608    ().startsWith("https:") || api.getWsdlUrl().startsWith("file:"))) {
1609  2 if (isWSDL2Document(api.getWsdlUrl())) {
1610  0 wsdlContentEle = wsdlReader.readAndCleanWsdl2(api);
1611  0 wsdlResource.setContent(wsdlContentEle.toString());
1612    } else {
1613  2 wsdlContentEle = wsdlReader.readAndCleanWsdl(api);
1614  2 wsdlResource.setContent(wsdlContentEle.toString());
1615    }
1616   
1617  2 registry.put(wsdlResourcePath, wsdlResource);
1618    //set the anonymous role for wsld resource to avoid basicauth security.
1619  2 String[] visibleRoles = null;
1620  2 if (api.getVisibleRoles() != null) {
1621  2 visibleRoles = api.getVisibleRoles().split(",");
1622    }
1623  2 setResourcePermissions(api.getId().getProviderName(), api.getVisibility(), visibleRoles, wsdlResourcePath);
1624    } else {
1625  0 byte[] wsdl = (byte[]) registry.get(wsdlResourcePath).getContent();
1626  0 if (isWSDL2Resource(wsdl)) {
1627  0 wsdlContentEle = wsdlReader.updateWSDL2(wsdl, api);
1628  0 wsdlResource.setContent(wsdlContentEle.toString());
1629    } else {
1630  0 wsdlContentEle = wsdlReader.updateWSDL(wsdl, api);
1631  0 wsdlResource.setContent(wsdlContentEle.toString());
1632    }
1633   
1634  0 registry.put(wsdlResourcePath, wsdlResource);
1635    //set the anonymous role for wsld resource to avoid basicauth security.
1636  0 String[] visibleRoles = null;
1637  0 if (api.getVisibleRoles() != null) {
1638  0 visibleRoles = api.getVisibleRoles().split(",");
1639    }
1640  0 setResourcePermissions(api.getId().getProviderName(), api.getVisibility(), visibleRoles, wsdlResourcePath);
1641    }
1642   
1643    //set the wsdl resource permlink as the wsdlURL.
1644  2 api.setWsdlUrl(getRegistryResourceHTTPPermlink(absoluteWSDLResourcePath));
1645   
1646  2 return wsdlResourcePath;
1647   
1648    } catch (RegistryException e) {
1649  0 String msg = "Failed to add WSDL " + api.getWsdlUrl() + " to the registry";
1650  0 log.error(msg, e);
1651  0 throw new RegistryException(msg, e);
1652    } catch (APIManagementException e) {
1653  0 String msg = "Failed to process the WSDL : " + api.getWsdlUrl();
1654  0 log.error(msg, e);
1655  0 throw new APIManagementException(msg, e);
1656    }
1657    }
1658   
1659    /**
1660    * Given a URL, this method checks if the underlying document is a WSDL2
1661    *
1662    * @param url URL to check
1663    * @return true if the underlying document is a WSDL2
1664    * @throws APIManagementException if error occurred while validating the URI
1665    */
 
1666  2 toggle public static boolean isWSDL2Document(String url) throws APIManagementException {
1667  2 APIMWSDLReader wsdlReader = new APIMWSDLReader(url);
1668  2 return wsdlReader.isWSDL2BaseURI();
1669    }
1670   
1671    /**
1672    * Given a wsdl resource, this method checks if the underlying document is a WSDL2
1673    *
1674    * @param wsdl byte array of wsdl definition saved in registry
1675    * @return true if wsdl2 definition
1676    * @throws APIManagementException
1677    */
 
1678  0 toggle private static boolean isWSDL2Resource(byte[] wsdl) throws APIManagementException {
1679  0 String wsdl2NameSpace = "http://www.w3.org/ns/wsdl";
1680  0 String wsdlContent = new String(wsdl);
1681  0 return wsdlContent.indexOf(wsdl2NameSpace) > 0;
1682    }
1683   
1684    /**
1685    * Read the GateWay Endpoint from the APIConfiguration. If multiple Gateway
1686    * environments defined,
1687    * take only the production node's Endpoint.
1688    * Else, pick what is available as the gateway node.
1689    *
1690    * @return {@link String} - Gateway URL
1691    */
1692   
 
1693  12 toggle public static String getGatewayendpoint(String transports) {
1694   
1695  12 String gatewayURLs;
1696   
1697  12 Map<String, Environment> gatewayEnvironments = ServiceReferenceHolder.getInstance()
1698    .getAPIManagerConfigurationService()
1699    .getAPIManagerConfiguration()
1700    .getApiGatewayEnvironments();
1701  12 if (gatewayEnvironments.size() > 1) {
1702  12 for (Environment environment : gatewayEnvironments.values()) {
1703  12 if (APIConstants.GATEWAY_ENV_TYPE_HYBRID.equals(environment.getType())) {
1704  12 gatewayURLs = environment.getApiGatewayEndpoint(); // This might have http,https
1705    // pick correct endpoint
1706  12 return APIUtil.extractHTTPSEndpoint(gatewayURLs, transports);
1707    }
1708    }
1709  0 for (Environment environment : gatewayEnvironments.values()) {
1710  0 if (APIConstants.GATEWAY_ENV_TYPE_PRODUCTION.equals(environment.getType())) {
1711  0 gatewayURLs = environment.getApiGatewayEndpoint(); // This might have http,https
1712    // pick correct endpoint
1713  0 return APIUtil.extractHTTPSEndpoint(gatewayURLs, transports);
1714    }
1715    }
1716  0 for (Environment environment : gatewayEnvironments.values()) {
1717  0 if (APIConstants.GATEWAY_ENV_TYPE_SANDBOX.equals(environment.getType())) {
1718  0 gatewayURLs = environment.getApiGatewayEndpoint(); // This might have http,https
1719    // pick correct endpoint
1720  0 return APIUtil.extractHTTPSEndpoint(gatewayURLs, transports);
1721    }
1722    }
1723    } else {
1724  0 gatewayURLs = ((Environment) gatewayEnvironments.values().toArray()[0]).getApiGatewayEndpoint();
1725  0 return extractHTTPSEndpoint(gatewayURLs, transports);
1726    }
1727   
1728  0 return null;
1729    }
1730   
1731    /**
1732    * Read the GateWay Endpoint from the APIConfiguration. If multiple Gateway
1733    * environments defined, get the gateway endpoint according to the environment type
1734    *
1735    * @param transports transports allowed for gateway endpoint
1736    * @param environmentName gateway environment name
1737    * @param environmentType gateway environment type
1738    * @return Gateway URL
1739    */
 
1740  0 toggle public static String getGatewayEndpoint(String transports, String environmentName, String environmentType)
1741    throws APIManagementException {
1742  0 String gatewayURLs;
1743  0 String gatewayEndpoint = "";
1744   
1745  0 Map<String, Environment> gatewayEnvironments = ServiceReferenceHolder.getInstance()
1746    .getAPIManagerConfigurationService().getAPIManagerConfiguration().getApiGatewayEnvironments();
1747  0 Environment environment = gatewayEnvironments.get(environmentName);
1748  0 if(environment.getType().equals(environmentType)) {
1749  0 gatewayURLs = environment.getApiGatewayEndpoint();
1750  0 gatewayEndpoint = extractHTTPSEndpoint(gatewayURLs, transports);
1751  0 if (log.isDebugEnabled()) {
1752  0 log.debug("Gateway urls are: " + gatewayURLs + " and the url with the correct transport is: "
1753    + gatewayEndpoint);
1754    }
1755    } else {
1756  0 handleException("Environment type mismatch for environment: " + environmentName +
1757    " for the environment types: " + environment.getType() + " and " + environmentType);
1758    }
1759  0 return gatewayEndpoint;
1760    }
1761   
1762    /**
1763    * Gateway endpoint has HTTP and HTTPS endpoints.
1764    * If both are defined pick HTTPS only. Else, pick whatever available.
1765    * eg: <GatewayEndpoint>http://${carbon.local.ip}:${http.nio.port},
1766    * https://${carbon.local.ip}:${https.nio.port}</GatewayEndpoint>
1767    *
1768    * @param gatewayURLs - String contains comma separated gateway urls.
1769    * @return {@link String} - Returns HTTPS gateway endpoint
1770    */
1771   
 
1772  12 toggle private static String extractHTTPSEndpoint(String gatewayURLs, String transports) {
1773  12 String gatewayURL;
1774  12 String gatewayHTTPURL = null;
1775  12 String gatewayHTTPSURL = null;
1776  12 boolean httpsEnabled = false;
1777  12 String[] gatewayURLsArray = gatewayURLs.split(",");
1778  12 String[] transportsArray = transports.split(",");
1779   
1780  12 for (String transport : transportsArray) {
1781  12 if (transport.startsWith(APIConstants.HTTPS_PROTOCOL)) {
1782  6 httpsEnabled = true;
1783    }
1784    }
1785  12 if (gatewayURLsArray.length > 1) {
1786  12 for (String url : gatewayURLsArray) {
1787  24 if (url.startsWith("https:")) {
1788  12 gatewayHTTPSURL = url;
1789    } else {
1790  12 if (!url.startsWith("ws:")) {
1791  12 gatewayHTTPURL = url;
1792    }
1793    }
1794    }
1795   
1796  12 if (httpsEnabled) {
1797  6 gatewayURL = gatewayHTTPSURL;
1798    } else {
1799  6 gatewayURL = gatewayHTTPURL;
1800    }
1801    } else {
1802  0 gatewayURL = gatewayURLs;
1803    }
1804  12 return gatewayURL;
1805    }
1806   
1807    /**
1808    * Create an Endpoint
1809    *
1810    * @param endpointUrl Endpoint url
1811    * @param registry Registry space to save the endpoint
1812    * @return Path of the created resource
1813    * @throws APIManagementException If an error occurs while adding the endpoint
1814    */
 
1815  0 toggle public static String createEndpoint(String endpointUrl, Registry registry) throws APIManagementException {
1816  0 try {
1817  0 EndpointManager endpointManager = new EndpointManager(registry);
1818  0 Endpoint endpoint = endpointManager.newEndpoint(endpointUrl);
1819  0 endpointManager.addEndpoint(endpoint);
1820  0 return GovernanceUtils.getArtifactPath(registry, endpoint.getId());
1821    } catch (RegistryException e) {
1822  0 String msg = "Failed to import endpoint " + endpointUrl + " to registry ";
1823  0 log.error(msg, e);
1824  0 throw new APIManagementException(msg, e);
1825    }
1826    }
1827   
1828    /**
1829    * Sorts the list of tiers according to the number of requests allowed per minute in each tier in descending order.
1830    *
1831    * @param tiers - The list of tiers to be sorted
1832    * @return - The sorted list.
1833    */
 
1834  25 toggle public static List<Tier> sortTiers(Set<Tier> tiers) {
1835  25 List<Tier> tierList = new ArrayList<Tier>();
1836  25 tierList.addAll(tiers);
1837  25 Collections.sort(tierList);
1838  25 return tierList;
1839    }
1840   
1841    /**
1842    * Returns a set of External API Stores as defined in the underlying governance
1843    * registry.
1844    *
1845    * @return a Map of tier names and Tier objects - possibly empty
1846    * @throws APIManagementException if an error occurs when loading tiers from the registry
1847    */
 
1848  618 toggle public static Set<APIStore> getExternalStores(int tenantId) throws APIManagementException {
1849    // First checking if ExternalStores are defined in api-manager.xml
1850  618 Set<APIStore> externalAPIStores = ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService()
1851    .getAPIManagerConfiguration().getExternalAPIStores();
1852    // If defined, return Store Config provided there.
1853  618 if (externalAPIStores != null && !externalAPIStores.isEmpty()) {
1854  0 return externalAPIStores;
1855    }
1856    // Else Read the config from Tenant's Registry.
1857  618 externalAPIStores = new HashSet<APIStore>();
1858  618 try {
1859  618 UserRegistry registry = ServiceReferenceHolder.getInstance().getRegistryService()
1860    .getGovernanceSystemRegistry(tenantId);
1861  618 if (registry.resourceExists(APIConstants.EXTERNAL_API_STORES_LOCATION)) {
1862  618 Resource resource = registry.get(APIConstants.EXTERNAL_API_STORES_LOCATION);
1863  618 String content = new String((byte[]) resource.getContent(), Charset.defaultCharset());
1864  618 OMElement element = AXIOMUtil.stringToOM(content);
1865  618 Iterator apistoreIterator = element.getChildrenWithLocalName("ExternalAPIStore");
1866   
1867  618 while (apistoreIterator.hasNext()) {
1868  0 APIStore store = new APIStore();
1869  0 OMElement storeElem = (OMElement) apistoreIterator.next();
1870  0 String type = storeElem.getAttributeValue(new QName(APIConstants.EXTERNAL_API_STORE_TYPE));
1871  0 String className =
1872    storeElem.getAttributeValue(new QName(APIConstants.EXTERNAL_API_STORE_CLASS_NAME));
1873  0 store.setPublisher((APIPublisher) getClassForName(className).newInstance());
1874  0 store.setType(type); //Set Store type [eg:wso2]
1875  0 String name = storeElem.getAttributeValue(new QName(APIConstants.EXTERNAL_API_STORE_ID));
1876  0 if (name == null) {
1877  0 log.error("The ExternalAPIStore name attribute is not defined in api-manager.xml.");
1878    }
1879  0 store.setName(name); //Set store name
1880  0 OMElement configDisplayName = storeElem.getFirstChildWithName
1881    (new QName(APIConstants.EXTERNAL_API_STORE_DISPLAY_NAME));
1882  0 String displayName = (configDisplayName != null) ? replaceSystemProperty(
1883    configDisplayName.getText()) : name;
1884  0 store.setDisplayName(displayName);//Set store display name
1885  0 store.setEndpoint(replaceSystemProperty(storeElem.getFirstChildWithName(
1886    new QName(APIConstants.EXTERNAL_API_STORE_ENDPOINT)).getText()));
1887    //Set store endpoint, which is used to publish APIs
1888  0 store.setPublished(false);
1889  0 if (APIConstants.WSO2_API_STORE_TYPE.equals(type)) {
1890  0 OMElement password = storeElem.getFirstChildWithName(new QName(
1891    APIConstants.EXTERNAL_API_STORE_PASSWORD));
1892  0 if (password != null) {
1893   
1894  0 String value = password.getText();
1895   
1896  0 store.setPassword(replaceSystemProperty(value));
1897  0 store.setUsername(replaceSystemProperty(storeElem.getFirstChildWithName(
1898    new QName(APIConstants.EXTERNAL_API_STORE_USERNAME)).getText()));
1899    //Set store login username
1900    } else {
1901  0 log.error("The user-credentials of API Publisher is not defined in the <ExternalAPIStore> " +
1902    "config of api-manager.xml.");
1903    }
1904    }
1905  0 externalAPIStores.add(store);
1906    }
1907   
1908    }
1909    } catch (RegistryException e) {
1910  0 String msg = "Error while retrieving External Stores Configuration from registry";
1911  0 log.error(msg, e);
1912  0 throw new APIManagementException(msg, e);
1913    } catch (XMLStreamException e) {
1914  0 String msg = "Malformed XML found in the External Stores Configuration resource";
1915  0 log.error(msg, e);
1916  0 throw new APIManagementException(msg, e);
1917    } catch (ClassNotFoundException e) {
1918  0 String msg = "One or more classes defined in APIConstants.EXTERNAL_API_STORE_CLASS_NAME cannot be found";
1919  0 log.error(msg, e);
1920  0 throw new APIManagementException(msg, e);
1921    } catch (InstantiationException e) {
1922  0 String msg = "One or more classes defined in APIConstants.EXTERNAL_API_STORE_CLASS_NAME cannot be load";
1923  0 log.error(msg, e);
1924  0 throw new APIManagementException(msg, e);
1925    } catch (IllegalAccessException e) {
1926  0 String msg = "One or more classes defined in APIConstants.EXTERNAL_API_STORE_CLASS_NAME cannot be access";
1927  0 log.error(msg, e);
1928  0 throw new APIManagementException(msg, e);
1929    }
1930  618 return externalAPIStores;
1931    }
1932   
1933   
1934    /**
1935    * Returns the External API Store Configuration with the given Store Name
1936    *
1937    * @param apiStoreName
1938    * @return
1939    * @throws APIManagementException
1940    */
 
1941  0 toggle public static APIStore getExternalAPIStore(String apiStoreName, int tenantId) throws APIManagementException {
1942  0 Set<APIStore> externalAPIStoresConfig = APIUtil.getExternalStores(tenantId);
1943  0 for (APIStore apiStoreConfig : externalAPIStoresConfig) {
1944  0 if (apiStoreConfig.getName().equals(apiStoreName)) {
1945  0 return apiStoreConfig;
1946    }
1947    }
1948  0 return null;
1949    }
1950   
1951    /**
1952    * Returns an unfiltered map of API availability tiers as defined in the underlying governance
1953    * registry.
1954    *
1955    * @return Map<String, Tier> an unfiltered Map of tier names and Tier objects - possibly empty
1956    * @throws APIManagementException if an error occurs when loading tiers from the registry
1957    */
 
1958  0 toggle public static Map<String, Tier> getAllTiers() throws APIManagementException {
1959  0 if (!APIUtil.isAdvanceThrottlingEnabled()) {
1960  0 try {
1961  0 Registry registry = ServiceReferenceHolder.getInstance().getRegistryService().
1962    getGovernanceSystemRegistry();
1963   
1964  0 return getAllTiers(registry, APIConstants.API_TIER_LOCATION, MultitenantConstants.SUPER_TENANT_ID);
1965    } catch (RegistryException e) {
1966  0 log.error(APIConstants.MSG_TIER_RET_ERROR, e);
1967  0 throw new APIManagementException(APIConstants.MSG_TIER_RET_ERROR, e);
1968    } catch (XMLStreamException e) {
1969  0 log.error(APIConstants.MSG_MALFORMED_XML_ERROR, e);
1970  0 throw new APIManagementException(APIConstants.MSG_MALFORMED_XML_ERROR, e);
1971    }
1972    } else {
1973  0 return getTiersFromPolicies(PolicyConstants.POLICY_LEVEL_SUB, MultitenantConstants.SUPER_TENANT_ID);
1974    }
1975    }
1976   
1977    /**
1978    * Returns an unfiltered map of API availability tiers of the tenant as defined in the underlying governance
1979    * registry.
1980    *
1981    * @return Map<String, Tier> an unfiltered Map of tier names and Tier objects - possibly empty
1982    * @throws APIManagementException if an error occurs when loading tiers from the registry
1983    */
 
1984  13 toggle public static Map<String, Tier> getAllTiers(int tenantId) throws APIManagementException {
1985  13 if (!APIUtil.isAdvanceThrottlingEnabled()) {
1986  13 try {
1987  13 Registry registry = ServiceReferenceHolder.getInstance().getRegistryService().
1988    getGovernanceSystemRegistry(tenantId);
1989   
1990  13 return getAllTiers(registry, APIConstants.API_TIER_LOCATION, tenantId);
1991    } catch (RegistryException e) {
1992  0 log.error(APIConstants.MSG_TIER_RET_ERROR, e);
1993  0 throw new APIManagementException(APIConstants.MSG_TIER_RET_ERROR, e);
1994    } catch (XMLStreamException e) {
1995  0 log.error(APIConstants.MSG_MALFORMED_XML_ERROR, e);
1996  0 throw new APIManagementException(APIConstants.MSG_MALFORMED_XML_ERROR, e);
1997    }
1998    } else {
1999  0 return getTiersFromPolicies(PolicyConstants.POLICY_LEVEL_SUB, tenantId);
2000    }
2001    }
2002   
2003    /**
2004    * Returns a map of API availability tiers as defined in the underlying governance
2005    * registry.
2006    *
2007    * @return a Map of tier names and Tier objects - possibly empty
2008    * @throws APIManagementException if an error occurs when loading tiers from the registry
2009    */
 
2010  0 toggle public static Map<String, Tier> getTiers() throws APIManagementException {
2011  0 if (!APIUtil.isAdvanceThrottlingEnabled()) {
2012  0 try {
2013  0 Registry registry = ServiceReferenceHolder.getInstance().getRegistryService().
2014    getGovernanceSystemRegistry();
2015  0 return getTiers(registry, APIConstants.API_TIER_LOCATION, MultitenantConstants.SUPER_TENANT_ID);
2016    } catch (RegistryException e) {
2017  0 log.error(APIConstants.MSG_TIER_RET_ERROR, e);
2018  0 throw new APIManagementException(APIConstants.MSG_TIER_RET_ERROR, e);
2019    }
2020    } else {
2021  0 return getTiersFromPolicies(PolicyConstants.POLICY_LEVEL_SUB, MultitenantConstants.SUPER_TENANT_ID);
2022    }
2023    }
2024   
2025   
2026    /**
2027    * Returns a map of API availability tiers as defined in the underlying governance
2028    * registry.
2029    *
2030    * @return a Map of tier names and Tier objects - possibly empty
2031    * @throws APIManagementException if an error occurs when loading tiers from the registry
2032    */
 
2033  0 toggle public static Map<String, Tier> getAdvancedSubsriptionTiers() throws APIManagementException {
2034  0 return getAdvancedSubsriptionTiers(MultitenantConstants.SUPER_TENANT_ID);
2035    }
2036   
2037    /**
2038    * Returns a map of API subscription tiers of the tenant as defined in database
2039    * registry.
2040    *
2041    * @return a Map of tier names and Tier objects - possibly empty
2042    * @throws APIManagementException if an error occurs when loading tiers from the registry
2043    */
 
2044  57 toggle public static Map<String, Tier> getAdvancedSubsriptionTiers(int tenantId) throws APIManagementException {
2045  57 return APIUtil.getTiersFromPolicies(PolicyConstants.POLICY_LEVEL_SUB, tenantId);
2046    }
2047   
2048    /**
2049    * Returns a map of API availability tiers of the tenant as defined in the underlying governance
2050    * registry.
2051    *
2052    * @return a Map of tier names and Tier objects - possibly empty
2053    * @throws APIManagementException if an error occurs when loading tiers from the registry
2054    */
 
2055  3002 toggle public static Map<String, Tier> getTiers(int tenantId) throws APIManagementException {
2056  3002 if (!APIUtil.isAdvanceThrottlingEnabled()) {
2057  159 try {
2058  159 Registry registry = ServiceReferenceHolder.getInstance().getRegistryService().
2059    getGovernanceSystemRegistry(tenantId);
2060  159 return getTiers(registry, APIConstants.API_TIER_LOCATION, tenantId);
2061    } catch (RegistryException e) {
2062  0 log.error(APIConstants.MSG_TIER_RET_ERROR, e);
2063  0 throw new APIManagementException(APIConstants.MSG_TIER_RET_ERROR, e);
2064    }
2065    } else {
2066  2843 return getTiersFromPolicies(PolicyConstants.POLICY_LEVEL_SUB, tenantId);
2067    }
2068    }
2069   
2070    /**
2071    * Returns a map of API availability tiers of the tenant as defined in the underlying governance
2072    * registry.
2073    *
2074    * @return a Map of tier names and Tier objects - possibly empty
2075    * @throws APIManagementException if an error occurs when loading tiers from the registry
2076    */
 
2077  150 toggle public static Map<String, Tier> getTiers(int tierType, String tenantDomain) throws APIManagementException {
2078  150 if (!APIUtil.isAdvanceThrottlingEnabled()) {
2079  13 boolean isTenantFlowStarted = false;
2080  13 try {
2081  13 PrivilegedCarbonContext.startTenantFlow();
2082  13 isTenantFlowStarted = true;
2083   
2084  13 PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
2085  13 int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
2086   
2087  13 Registry registry = ServiceReferenceHolder.getInstance().getRegistryService().
2088    getGovernanceSystemRegistry(tenantId);
2089   
2090  13 if (tierType == APIConstants.TIER_API_TYPE) {
2091  5 return getTiers(registry, APIConstants.API_TIER_LOCATION, tenantId);
2092  8 } else if (tierType == APIConstants.TIER_RESOURCE_TYPE) {
2093  2 return getTiers(registry, APIConstants.RES_TIER_LOCATION, tenantId);
2094  6 } else if (tierType == APIConstants.TIER_APPLICATION_TYPE) {
2095  6 return getTiers(registry, APIConstants.APP_TIER_LOCATION, tenantId);
2096    } else {
2097  0 throw new APIManagementException("No such a tier type : " + tierType);
2098    }
2099    } catch (RegistryException e) {
2100  0 log.error(APIConstants.MSG_TIER_RET_ERROR, e);
2101  0 throw new APIManagementException(APIConstants.MSG_TIER_RET_ERROR, e);
2102    } finally {
2103  13 if (isTenantFlowStarted) {
2104  13 PrivilegedCarbonContext.endTenantFlow();
2105    }
2106    }
2107    } else {
2108  137 boolean isTenantFlowStarted = false;
2109  137 try {
2110  137 PrivilegedCarbonContext.startTenantFlow();
2111  137 isTenantFlowStarted = true;
2112  137 PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
2113  137 int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
2114  137 if (tierType == APIConstants.TIER_API_TYPE) {
2115  0 return getTiersFromPolicies(PolicyConstants.POLICY_LEVEL_SUB, tenantId);
2116  137 } else if (tierType == APIConstants.TIER_RESOURCE_TYPE) {
2117  0 return getTiersFromPolicies(PolicyConstants.POLICY_LEVEL_API, tenantId);
2118  137 } else if (tierType == APIConstants.TIER_APPLICATION_TYPE) {
2119  137 return getTiersFromPolicies(PolicyConstants.POLICY_LEVEL_APP, tenantId);
2120    } else {
2121  0 throw new APIManagementException("No such a tier type : " + tierType);
2122    }
2123    } finally {
2124  137 if (isTenantFlowStarted) {
2125  137 PrivilegedCarbonContext.endTenantFlow();
2126    }
2127    }
2128    }
2129    }
2130   
2131   
2132    /**
2133    * Retrieves unfiltered list of all available tiers from registry.
2134    * Result will contains all the tiers including unauthenticated tier which is
2135    * filtered out in getTiers}
2136    *
2137    * @param registry registry to access tiers config
2138    * @param tierLocation registry location of tiers config
2139    * @return Map<String, Tier> containing all available tiers
2140    * @throws RegistryException when registry action fails
2141    * @throws XMLStreamException when xml parsing fails
2142    * @throws APIManagementException when fails to retrieve tier attributes
2143    */
 
2144  185 toggle private static Map<String, Tier> getAllTiers(Registry registry, String tierLocation, int tenantId)
2145    throws RegistryException, XMLStreamException, APIManagementException {
2146    // We use a treeMap here to keep the order
2147  185 Map<String, Tier> tiers = new TreeMap<String, Tier>();
2148   
2149  185 if (registry.resourceExists(tierLocation)) {
2150  185 Resource resource = registry.get(tierLocation);
2151  185 String content = new String((byte[]) resource.getContent(), Charset.defaultCharset());
2152   
2153  185 OMElement element = AXIOMUtil.stringToOM(content);
2154  185 OMElement assertion = element.getFirstChildWithName(APIConstants.ASSERTION_ELEMENT);
2155  185 Iterator policies = assertion.getChildrenWithName(APIConstants.POLICY_ELEMENT);
2156   
2157  1159 while (policies.hasNext()) {
2158  974 OMElement policy = (OMElement) policies.next();
2159  974 OMElement id = policy.getFirstChildWithName(APIConstants.THROTTLE_ID_ELEMENT);
2160   
2161  974 String tierName = id.getText();
2162   
2163    // Constructing the tier object
2164  974 Tier tier = new Tier(tierName);
2165  974 tier.setPolicyContent(policy.toString().getBytes(Charset.defaultCharset()));
2166   
2167  974 if (id.getAttribute(APIConstants.THROTTLE_ID_DISPLAY_NAME_ELEMENT) != null) {
2168  0 tier.setDisplayName(id.getAttributeValue(APIConstants.THROTTLE_ID_DISPLAY_NAME_ELEMENT));
2169    } else {
2170  974 tier.setDisplayName(tierName);
2171    }
2172  974 String desc;
2173  974 try {
2174  974 long requestPerMin = APIDescriptionGenUtil.getAllowedCountPerMinute(policy);
2175  974 tier.setRequestsPerMin(requestPerMin);
2176   
2177  974 long requestCount = APIDescriptionGenUtil.getAllowedRequestCount(policy);
2178  974 tier.setRequestCount(requestCount);
2179   
2180  974 long unitTime = APIDescriptionGenUtil.getTimeDuration(policy);
2181  974 tier.setUnitTime(unitTime);
2182   
2183  974 if (requestPerMin >= 1) {
2184  974 desc = DESCRIPTION.replaceAll("\\[1\\]", Long.toString(requestPerMin));
2185    } else {
2186  0 desc = DESCRIPTION;
2187    }
2188  974 tier.setDescription(desc);
2189   
2190    } catch (APIManagementException ex) {
2191    // If there is any issue in getting the request counts or the time duration, that means this tier
2192    // information can not be used for throttling. Hence we log this exception and continue the flow
2193    // to the next tier.
2194  0 log.warn("Unable to get the request count/time duration information for : " + tier.getName() + ". "
2195    + ex.getMessage());
2196  0 continue;
2197    }
2198   
2199   
2200    // Get all the attributes of the tier.
2201  974 Map<String, Object> tierAttributes = APIDescriptionGenUtil.getTierAttributes(policy);
2202  974 if (!tierAttributes.isEmpty()) {
2203    // The description, billing plan and the stop on quota reach properties are also stored as attributes
2204    // of the tier attributes. Hence we extract them from the above attributes map.
2205  405 Iterator<Entry<String, Object>> attributeIterator = tierAttributes.entrySet().iterator();
2206  1321 while (attributeIterator.hasNext()) {
2207  916 Entry<String, Object> entry = attributeIterator.next();
2208   
2209  916 if (APIConstants.THROTTLE_TIER_DESCRIPTION_ATTRIBUTE.equals(entry.getKey())
2210    && entry.getValue() instanceof String) {
2211   
2212  106 tier.setDescription((String) entry.getValue());
2213   
2214    // We remove the attribute from the map
2215  106 attributeIterator.remove();
2216  106 continue;
2217   
2218    }
2219  810 if (APIConstants.THROTTLE_TIER_PLAN_ATTRIBUTE.equals(entry.getKey())
2220    && entry.getValue() instanceof String) {
2221   
2222  277 tier.setTierPlan((String) entry.getValue());
2223   
2224    // We remove the attribute from the map
2225  277 attributeIterator.remove();
2226  277 continue;
2227   
2228    }
2229  533 if (APIConstants.THROTTLE_TIER_QUOTA_ACTION_ATTRIBUTE.equals(entry.getKey())
2230    && entry.getValue() instanceof String) {
2231   
2232  277 tier.setStopOnQuotaReached(Boolean.parseBoolean((String) entry.getValue()));
2233   
2234    // We remove the attribute from the map
2235  277 attributeIterator.remove();
2236    // We do not need a continue since this is the last statement.
2237   
2238    }
2239    }
2240  405 tier.setTierAttributes(tierAttributes);
2241    }
2242  974 tiers.put(tierName, tier);
2243    }
2244    }
2245   
2246  185 if (isEnabledUnlimitedTier()) {
2247  185 Tier tier = new Tier(APIConstants.UNLIMITED_TIER);
2248  185 tier.setDescription(APIConstants.UNLIMITED_TIER_DESC);
2249  185 tier.setDisplayName(APIConstants.UNLIMITED_TIER);
2250  185 tier.setRequestsPerMin(Long.MAX_VALUE);
2251   
2252  185 if (isUnlimitedTierPaid(getTenantDomainFromTenantId(tenantId))) {
2253  0 tier.setTierPlan(APIConstants.COMMERCIAL_TIER_PLAN);
2254    } else {
2255  185 tier.setTierPlan(APIConstants.BILLING_PLAN_FREE);
2256    }
2257   
2258  185 tiers.put(tier.getName(), tier);
2259    }
2260   
2261  185 return tiers;
2262    }
2263   
2264    /**
2265    * Retrieves filtered list of available tiers from registry. This method will not return Unauthenticated
2266    * tier in the list. Use to retrieve all tiers without
2267    * any filtering.
2268    *
2269    * @param registry registry to access tiers config
2270    * @param tierLocation registry location of tiers config
2271    * @return map containing available tiers
2272    * @throws APIManagementException when fails to retrieve tier attributes
2273    */
 
2274  172 toggle private static Map<String, Tier> getTiers(Registry registry, String tierLocation, int tenantId) throws APIManagementException {
2275  172 Map<String, Tier> tiers = null;
2276  172 try {
2277  172 tiers = getAllTiers(registry, tierLocation, tenantId);
2278  172 tiers.remove(APIConstants.UNAUTHENTICATED_TIER);
2279    } catch (RegistryException e) {
2280  0 handleException(APIConstants.MSG_TIER_RET_ERROR, e);
2281    } catch (XMLStreamException e) {
2282  0 handleException(APIConstants.MSG_MALFORMED_XML_ERROR, e);
2283    } catch (APIManagementException e) {
2284  0 handleException("Unable to get tier attributes", e);
2285    } catch (Exception e) {
2286   
2287    // generic exception is caught to catch exceptions thrown from map remove method
2288  0 handleException("Unable to remove Unauthenticated tier from tiers list", e);
2289    }
2290  172 return tiers;
2291    }
2292   
2293    /**
2294    * This method deletes a given tier from tier xml file, for a given tenant
2295    *
2296    * @param tier tier to be deleted
2297    * @param tenantId id of the tenant
2298    * @throws APIManagementException if error occurs while getting registry resource or processing XML
2299    */
 
2300  0 toggle public static void deleteTier(Tier tier, int tenantId) throws APIManagementException {
2301  0 try {
2302  0 Registry registry = ServiceReferenceHolder.getInstance().getRegistryService().
2303    getGovernanceSystemRegistry(tenantId);
2304  0 if (registry.resourceExists(APIConstants.API_TIER_LOCATION)) {
2305  0 Resource resource = registry.get(APIConstants.API_TIER_LOCATION);
2306  0 String content = new String((byte[]) resource.getContent(), Charset.defaultCharset());
2307  0 OMElement element = AXIOMUtil.stringToOM(content);
2308  0 OMElement assertion = element.getFirstChildWithName(APIConstants.ASSERTION_ELEMENT);
2309  0 Iterator policies = assertion.getChildrenWithName(APIConstants.POLICY_ELEMENT);
2310  0 boolean foundTier = false;
2311   
2312  0 String tierName = null;
2313  0 while (policies.hasNext()) {
2314  0 OMElement policy = (OMElement) policies.next();
2315  0 OMElement id = policy.getFirstChildWithName(APIConstants.THROTTLE_ID_ELEMENT);
2316  0 tierName = tier.getName();
2317  0 if (tierName != null && tierName.equalsIgnoreCase(id.getText())) {
2318  0 foundTier = true;
2319  0 policies.remove();
2320  0 break;
2321    }
2322    }
2323  0 if (!foundTier) {
2324  0 log.error("Tier doesn't exist : " + tierName);
2325  0 throw new APIManagementException("Tier doesn't exist : " + tierName);
2326    }
2327  0 resource.setContent(element.toString());
2328  0 registry.put(APIConstants.API_TIER_LOCATION, resource);
2329    }
2330    } catch (RegistryException e) {
2331  0 log.error(APIConstants.MSG_TIER_RET_ERROR, e);
2332  0 throw new APIManagementException(e.getMessage());
2333    } catch (XMLStreamException e) {
2334  0 log.error(APIConstants.MSG_MALFORMED_XML_ERROR, e);
2335  0 throw new APIManagementException(e.getMessage());
2336    }
2337    }
2338   
2339    /**
2340    * Returns the tier display name for a particular tier
2341    *
2342    * @return the relevant tier display name
2343    * @throws APIManagementException if an error occurs when loading tiers from the registry
2344    */
 
2345  0 toggle public static String getTierDisplayName(int tenantId, String tierName) throws APIManagementException {
2346  0 String displayName = null;
2347  0 if (APIConstants.UNLIMITED_TIER.equals(tierName)) {
2348  0 return APIConstants.UNLIMITED_TIER;
2349    }
2350  0 try {
2351  0 Registry registry = ServiceReferenceHolder.getInstance().getRegistryService().
2352    getGovernanceSystemRegistry(tenantId);
2353  0 if (registry.resourceExists(APIConstants.API_TIER_LOCATION)) {
2354  0 Resource resource = registry.get(APIConstants.API_TIER_LOCATION);
2355  0 String content = new String((byte[]) resource.getContent(), Charset.defaultCharset());
2356  0 OMElement element = AXIOMUtil.stringToOM(content);
2357  0 OMElement assertion = element.getFirstChildWithName(APIConstants.ASSERTION_ELEMENT);
2358  0 Iterator policies = assertion.getChildrenWithName(APIConstants.POLICY_ELEMENT);
2359   
2360  0 while (policies.hasNext()) {
2361  0 OMElement policy = (OMElement) policies.next();
2362  0 OMElement id = policy.getFirstChildWithName(APIConstants.THROTTLE_ID_ELEMENT);
2363  0 if (id.getText().equals(tierName)) {
2364  0 if (id.getAttribute(APIConstants.THROTTLE_ID_DISPLAY_NAME_ELEMENT) != null) {
2365  0 displayName = id.getAttributeValue(APIConstants.THROTTLE_ID_DISPLAY_NAME_ELEMENT);
2366  0 } else if (displayName == null) {
2367  0 displayName = id.getText();
2368    }
2369    }
2370    }
2371    }
2372    } catch (RegistryException e) {
2373  0 log.error(APIConstants.MSG_TIER_RET_ERROR, e);
2374  0 throw new APIManagementException(APIConstants.MSG_TIER_RET_ERROR, e);
2375    } catch (XMLStreamException e) {
2376  0 log.error(APIConstants.MSG_MALFORMED_XML_ERROR, e);
2377  0 throw new APIManagementException(APIConstants.MSG_MALFORMED_XML_ERROR, e);
2378    }
2379  0 return displayName;
2380    }
2381   
2382    /**
2383    * Checks whether the specified user has the specified permission.
2384    *
2385    * @param username A username
2386    * @param permission A valid Carbon permission
2387    * @throws APIManagementException If the user does not have the specified permission or if an error occurs
2388    */
 
2389  3291 toggle public static void checkPermission(String username, String permission)
2390    throws APIManagementException {
2391  3291 if (username == null) {
2392  8 throw new APIManagementException("Attempt to execute privileged operation as" +
2393    " the anonymous user");
2394    }
2395   
2396  3283 if (isPermissionCheckDisabled()) {
2397  0 log.debug("Permission verification is disabled by APIStore configuration");
2398  0 return;
2399    }
2400   
2401  3283 String tenantDomain = MultitenantUtils.getTenantDomain(username);
2402  3283 PrivilegedCarbonContext.startTenantFlow();
2403  3283 PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
2404   
2405  3283 boolean authorized;
2406  3283 try {
2407  3283 int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager().
2408    getTenantId(tenantDomain);
2409   
2410  3283 if (!org.wso2.carbon.utils.multitenancy.MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
2411  881 org.wso2.carbon.user.api.AuthorizationManager manager =
2412    ServiceReferenceHolder.getInstance()
2413    .getRealmService()
2414    .getTenantUserRealm(tenantId)
2415    .getAuthorizationManager();
2416  881 authorized =
2417    manager.isUserAuthorized(MultitenantUtils.getTenantAwareUsername(username), permission,
2418    CarbonConstants.UI_PERMISSION_ACTION);
2419    } else {
2420    // On the first login attempt to publisher (without browsing the
2421    // store), the user realm will be null.
2422  2402 if (ServiceReferenceHolder.getUserRealm() == null) {
2423  11 ServiceReferenceHolder.setUserRealm((UserRealm) ServiceReferenceHolder.getInstance()
2424    .getRealmService()
2425    .getTenantUserRealm(tenantId));
2426    }
2427  2402 authorized =
2428    AuthorizationManager.getInstance()
2429    .isUserAuthorized(MultitenantUtils.getTenantAwareUsername(username),
2430    permission);
2431    }
2432  3283 if (!authorized) {
2433  28 throw new APIManagementException("User '" + username + "' does not have the " +
2434    "required permission: " + permission);
2435    }
2436    } catch (UserStoreException e) {
2437  0 throw new APIManagementException("Error while checking the user:" + username + " authorized or not", e);
2438    } finally {
2439  3283 PrivilegedCarbonContext.endTenantFlow();
2440    }
2441    }
2442   
2443   
2444   
2445    /**
2446    * Checks whether the specified user has the specified permission.
2447    *
2448    * @param userNameWithoutChange A username
2449    * @param permission A valid Carbon permission
2450    * @throws APIManagementException If the user does not have the specified permission or if an error occurs
2451    */
 
2452  200 toggle public static boolean hasPermission(String userNameWithoutChange, String permission)
2453    throws APIManagementException {
2454  200 boolean authorized = false;
2455  200 if (userNameWithoutChange == null) {
2456  0 throw new APIManagementException("Attempt to execute privileged operation as" +
2457    " the anonymous user");
2458    }
2459   
2460  200 if (isPermissionCheckDisabled()) {
2461  0 log.debug("Permission verification is disabled by APIStore configuration");
2462  0 authorized = true;
2463  0 return authorized;
2464    }
2465   
2466  200 if (APIConstants.Permissions.APIM_ADMIN.equals(permission)) {
2467  132 Integer value = getValueFromCache(APIConstants.API_PUBLISHER_ADMIN_PERMISSION_CACHE, userNameWithoutChange);
2468  132 if (value != null) {
2469  114 return value == 1;
2470    }
2471    }
2472   
2473  86 String tenantDomain = MultitenantUtils.getTenantDomain(userNameWithoutChange);
2474  86 PrivilegedCarbonContext.startTenantFlow();
2475  86 PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
2476   
2477  86 try {
2478  86 int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager().
2479    getTenantId(tenantDomain);
2480   
2481  86 if (!org.wso2.carbon.utils.multitenancy.MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
2482  24 org.wso2.carbon.user.api.AuthorizationManager manager =
2483    ServiceReferenceHolder.getInstance()
2484    .getRealmService()
2485    .getTenantUserRealm(tenantId)
2486    .getAuthorizationManager();
2487  24 authorized =
2488    manager.isUserAuthorized(MultitenantUtils.getTenantAwareUsername(userNameWithoutChange), permission,
2489    CarbonConstants.UI_PERMISSION_ACTION);
2490    } else {
2491    // On the first login attempt to publisher (without browsing the
2492    // store), the user realm will be null.
2493  62 if (ServiceReferenceHolder.getUserRealm() == null) {
2494  0 ServiceReferenceHolder.setUserRealm((UserRealm) ServiceReferenceHolder.getInstance()
2495    .getRealmService()
2496    .getTenantUserRealm(tenantId));
2497    }
2498  62 authorized =
2499    AuthorizationManager.getInstance()
2500    .isUserAuthorized(MultitenantUtils.getTenantAwareUsername(userNameWithoutChange),
2501    permission);
2502    }
2503  86 if (APIConstants.Permissions.APIM_ADMIN.equals(permission)) {
2504  18 addToRolesCache(APIConstants.API_PUBLISHER_ADMIN_PERMISSION_CACHE, userNameWithoutChange,
2505  18 authorized ? 1 : 2);
2506    }
2507   
2508    } catch (UserStoreException e) {
2509  0 throw new APIManagementException("Error while checking the user:" + userNameWithoutChange + " authorized or not", e);
2510    } finally {
2511  86 PrivilegedCarbonContext.endTenantFlow();
2512    }
2513   
2514  86 return authorized;
2515    }
2516   
2517    /**
2518    * Checks whether the disablePermissionCheck parameter enabled
2519    *
2520    * @return boolean
2521    */
 
2522  3483 toggle public static boolean isPermissionCheckDisabled() {
2523  3483 APIManagerConfiguration config = ServiceReferenceHolder.getInstance().
2524    getAPIManagerConfigurationService().getAPIManagerConfiguration();
2525  3483 String disablePermissionCheck = config.getFirstProperty(APIConstants.API_STORE_DISABLE_PERMISSION_CHECK);
2526  3483 if (disablePermissionCheck == null) {
2527  3483 return false;
2528    }
2529   
2530  0 return Boolean.parseBoolean(disablePermissionCheck);
2531    }
2532   
2533    /**
2534    * Checks whether the specified user has the specified permission without throwing
2535    * any exceptions.
2536    *
2537    * @param username A username
2538    * @param permission A valid Carbon permission
2539    * @return true if the user has the specified permission and false otherwise
2540    */
 
2541  748 toggle public static boolean checkPermissionQuietly(String username, String permission) {
2542  748 try {
2543  748 checkPermission(username, permission);
2544  734 return true;
2545    } catch (APIManagementException ignore) {
2546    // Ignore the exception.
2547    // Logging it on debug mode so if needed we can see the exception stacktrace.
2548  14 if (log.isDebugEnabled()) {
2549  0 log.debug("User does not have permission", ignore);
2550    }
2551  14 return false;
2552    }
2553    }
2554   
2555    /**
2556    * Gets the information of the logged in User.
2557    *
2558    * @param cookie Cookie of the previously logged in session.
2559    * @param serviceUrl Url of the authentication service.
2560    * @return LoggedUserInfo object containing details of the logged in user.
2561    * @throws ExceptionException
2562    * @throws RemoteException
2563    */
 
2564  735 toggle public static LoggedUserInfo getLoggedInUserInfo(String cookie, String serviceUrl) throws RemoteException, ExceptionException {
2565  735 LoggedUserInfoAdminStub stub = new LoggedUserInfoAdminStub(null,
2566    serviceUrl + "LoggedUserInfoAdmin");
2567  735 ServiceClient client = stub._getServiceClient();
2568  735 Options options = client.getOptions();
2569  735 options.setManageSession(true);
2570  735 options.setProperty(HTTPConstants.COOKIE_STRING, cookie);
2571  735 return stub.getUserInfo();
2572    }
2573   
2574    /**
2575    * Get user profiles of user
2576    *
2577    * @param username username
2578    * @return default user profile of user
2579    * @throws APIManagementException
2580    */
 
2581  0 toggle public static UserProfileDTO getUserDefaultProfile(String username) throws APIManagementException {
2582  0 APIManagerConfiguration apiManagerConfiguration = ServiceReferenceHolder.getInstance()
2583    .getAPIManagerConfigurationService().getAPIManagerConfiguration();
2584  0 String url = apiManagerConfiguration.getFirstProperty(APIConstants.API_KEY_VALIDATOR_URL);
2585  0 String errorMsg = "Error while getting profile of user ";
2586  0 try {
2587  0 UserProfileMgtServiceStub stub = new UserProfileMgtServiceStub(
2588    ServiceReferenceHolder.getContextService().getClientConfigContext(),
2589    url + APIConstants.USER_PROFILE_MGT_SERVICE);
2590  0 ServiceClient gatewayServiceClient = stub._getServiceClient();
2591  0 CarbonUtils.setBasicAccessSecurityHeaders(
2592    apiManagerConfiguration.getFirstProperty(APIConstants.API_KEY_VALIDATOR_USERNAME),
2593    apiManagerConfiguration.getFirstProperty(APIConstants.API_KEY_VALIDATOR_PASSWORD),
2594    gatewayServiceClient);
2595  0 UserProfileDTO[] profiles = stub.getUserProfiles(username);
2596  0 for (UserProfileDTO dto : profiles) {
2597  0 if (APIConstants.USER_DEFAULT_PROFILE.equals(dto.getProfileName())) {
2598  0 return dto;
2599    }
2600    }
2601    } catch (AxisFault axisFault) {
2602    //here we are going to log the error message and return because in this case, current user cannot fetch
2603    //profile of another user (due to cross tenant isolation, not allowed to access user details etc.)
2604  0 log.error("Cannot access user profile of : " + username);
2605  0 return null;
2606    } catch (RemoteException e) {
2607  0 handleException(errorMsg + username, e);
2608    } catch (UserProfileMgtServiceUserProfileExceptionException e) {
2609  0 handleException(errorMsg + username, e);
2610    }
2611  0 return null;
2612    }
2613   
2614   
2615    /**
2616    * Retrieves the role list of a user
2617    *
2618    * @param username A username
2619    * @param username A username
2620    * @throws APIManagementException If an error occurs
2621    */
 
2622  25 toggle public static String[] getListOfRoles(String username) throws APIManagementException {
2623  25 if (username == null) {
2624  0 throw new APIManagementException("Attempt to execute privileged operation as" +
2625    " the anonymous user");
2626    }
2627   
2628  25 String[] roles = null;
2629   
2630  25 roles = getValueFromCache(APIConstants.API_USER_ROLE_CACHE, username);
2631  25 if (roles != null) {
2632  16 return roles;
2633    }
2634  9 String tenantDomain = MultitenantUtils.getTenantDomain(username);
2635  9 try {
2636  9 if (!org.wso2.carbon.utils.multitenancy.MultitenantConstants.SUPER_TENANT_DOMAIN_NAME
2637    .equals(tenantDomain)) {
2638  0 int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager()
2639    .getTenantId(tenantDomain);
2640  0 UserStoreManager manager = ServiceReferenceHolder.getInstance().getRealmService()
2641    .getTenantUserRealm(tenantId).getUserStoreManager();
2642  0 roles = manager.getRoleListOfUser(MultitenantUtils.getTenantAwareUsername(username));
2643    } else {
2644  9 roles = AuthorizationManager.getInstance()
2645    .getRolesOfUser(MultitenantUtils.getTenantAwareUsername(username));
2646    }
2647  9 addToRolesCache(APIConstants.API_USER_ROLE_CACHE, username, roles);
2648  9 return roles;
2649    } catch (UserStoreException e) {
2650  0 throw new APIManagementException("UserStoreException while trying the role list of the user " + username,
2651    e);
2652    }
2653    }
2654   
2655    /**
2656    * To add the value to a cache.
2657    *
2658    * @param cacheName - Name of the Cache
2659    * @param key - Key of the entry that need to be added.
2660    * @param value - Value of the entry that need to be added.
2661    */
 
2662  27 toggle protected static <T> void addToRolesCache(String cacheName, String key, T value) {
2663  27 if (isPublisherRoleCacheEnabled) {
2664  27 if (log.isDebugEnabled()) {
2665  0 log.debug("Publisher role cache is enabled, adding the roles for the " + key + " to the cache "
2666    + cacheName + "'");
2667    }
2668  27 Caching.getCacheManager(APIConstants.API_MANAGER_CACHE_MANAGER).getCache(cacheName).put(key, value);
2669    }
2670    }
2671   
2672    /**
2673    * To get the value from the cache.
2674    *
2675    * @param cacheName Name of the cache.
2676    * @param key Key of the cache entry.
2677    * @return Role list from the cache, if a values exists, otherwise null.
2678    */
 
2679  157 toggle protected static <T> T getValueFromCache(String cacheName, String key) {
2680  157 if (isPublisherRoleCacheEnabled) {
2681  157 if (log.isDebugEnabled()) {
2682  0 log.debug("Publisher role cache is enabled, retrieving the roles for " + key + " from the cache "
2683    + cacheName + "'");
2684    }
2685  157 Cache<String, T> rolesCache = Caching.getCacheManager(APIConstants.API_MANAGER_CACHE_MANAGER)
2686    .getCache(cacheName);
2687  157 return rolesCache.get(key);
2688    }
2689  0 return null;
2690    }
2691   
2692    /**
2693    * Retrieves the list of user roles without throwing any exceptions.
2694    *
2695    * @param username A username
2696    * @return the list of roles to which the user belongs to.
2697    */
 
2698  0 toggle public static String[] getListOfRolesQuietly(String username) {
2699  0 try {
2700  0 return getListOfRoles(username);
2701    } catch (APIManagementException e) {
2702  0 return new String[0];
2703    }
2704    }
2705   
2706    /**
2707    * Sets permission for uploaded file resource.
2708    *
2709    * @param filePath Registry path for the uploaded file
2710    * @throws APIManagementException
2711    */
2712   
 
2713  10 toggle public static void setFilePermission(String filePath) throws APIManagementException {
2714  10 try {
2715  10 String filePathString = filePath.replaceFirst("/registry/resource/", "");
2716  10 org.wso2.carbon.user.api.AuthorizationManager accessControlAdmin = ServiceReferenceHolder.getInstance().
2717    getRealmService().getTenantUserRealm(MultitenantConstants.SUPER_TENANT_ID).
2718    getAuthorizationManager();
2719  10 if (!accessControlAdmin.isRoleAuthorized(CarbonConstants.REGISTRY_ANONNYMOUS_ROLE_NAME,
2720    filePathString, ActionConstants.GET)) {
2721  10 accessControlAdmin.authorizeRole(CarbonConstants.REGISTRY_ANONNYMOUS_ROLE_NAME,
2722    filePathString, ActionConstants.GET);
2723    }
2724    } catch (UserStoreException e) {
2725  0 throw new APIManagementException("Error while setting up permissions for file location", e);
2726    }
2727    }
2728   
2729    /**
2730    * This method used to get API from governance artifact specific to copyAPI
2731    *
2732    * @param artifact API artifact
2733    * @param registry Registry
2734    * @return API
2735    * @throws APIManagementException if failed to get API from artifact
2736    */
 
2737  19 toggle public static API getAPI(GovernanceArtifact artifact, Registry registry, APIIdentifier oldId, String oldContext)
2738    throws APIManagementException {
2739   
2740  19 API api;
2741  19 try {
2742  19 String providerName = artifact.getAttribute(APIConstants.API_OVERVIEW_PROVIDER);
2743  19 String apiName = artifact.getAttribute(APIConstants.API_OVERVIEW_NAME);
2744  19 String apiVersion = artifact.getAttribute(APIConstants.API_OVERVIEW_VERSION);
2745  19 api = new API(new APIIdentifier(providerName, apiName, apiVersion));
2746  19 int apiId = ApiMgtDAO.getInstance().getAPIID(oldId, null);
2747  19 if (apiId == -1) {
2748  0 return null;
2749    }
2750    // set rating
2751  19 String artifactPath = GovernanceUtils.getArtifactPath(registry, artifact.getId());
2752  19 BigDecimal bigDecimal = BigDecimal.valueOf(registry.getAverageRating(artifactPath));
2753  19 BigDecimal res = bigDecimal.setScale(1, RoundingMode.HALF_UP);
2754  19 api.setRating(res.floatValue());
2755    //set description
2756  19 api.setDescription(artifact.getAttribute(APIConstants.API_OVERVIEW_DESCRIPTION));
2757    //set last access time
2758  19 api.setLastUpdated(registry.get(artifactPath).getLastModified());
2759    //set uuid
2760  19 api.setUUID(artifact.getId());
2761    // set url
2762  19 api.setStatus(getLcStateFromArtifact(artifact));
2763  19 api.setThumbnailUrl(artifact.getAttribute(APIConstants.API_OVERVIEW_THUMBNAIL_URL));
2764  19 api.setWsdlUrl(artifact.getAttribute(APIConstants.API_OVERVIEW_WSDL));
2765  19 api.setWadlUrl(artifact.getAttribute(APIConstants.API_OVERVIEW_WADL));
2766  19 api.setTechnicalOwner(artifact.getAttribute(APIConstants.API_OVERVIEW_TEC_OWNER));
2767  19 api.setTechnicalOwnerEmail(artifact.getAttribute(APIConstants.API_OVERVIEW_TEC_OWNER_EMAIL));
2768  19 api.setBusinessOwner(artifact.getAttribute(APIConstants.API_OVERVIEW_BUSS_OWNER));
2769  19 api.setBusinessOwnerEmail(artifact.getAttribute(APIConstants.API_OVERVIEW_BUSS_OWNER_EMAIL));
2770  19 api.setEndpointSecured(Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_SECURED)));
2771  19 api.setEndpointAuthDigest(Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_AUTH_DIGEST)));
2772  19 api.setEndpointUTUsername(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_USERNAME));
2773  19 if (!((APIConstants.DEFAULT_MODIFIED_ENDPOINT_PASSWORD)
2774    .equals(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_PASSWORD)))) {
2775  19 api.setEndpointUTPassword(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_PASSWORD));
2776    } else { //If APIEndpointPasswordRegistryHandler is enabled take password from the registry hidden property
2777  0 api.setEndpointUTPassword(getActualEpPswdFromHiddenProperty(api, registry));
2778    }
2779  19 api.setTransports(artifact.getAttribute(APIConstants.API_OVERVIEW_TRANSPORTS));
2780   
2781  19 api.setEndpointConfig(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_CONFIG));
2782   
2783  19 api.setRedirectURL(artifact.getAttribute(APIConstants.API_OVERVIEW_REDIRECT_URL));
2784  19 api.setApiOwner(artifact.getAttribute(APIConstants.API_OVERVIEW_OWNER));
2785  19 api.setAdvertiseOnly(Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_ADVERTISE_ONLY)));
2786   
2787  19 api.setSubscriptionAvailability(artifact.getAttribute(APIConstants.API_OVERVIEW_SUBSCRIPTION_AVAILABILITY));
2788  19 api.setSubscriptionAvailableTenants(artifact.getAttribute(APIConstants.API_OVERVIEW_SUBSCRIPTION_AVAILABLE_TENANTS));
2789   
2790  19 api.setResponseCache(artifact.getAttribute(APIConstants.API_OVERVIEW_RESPONSE_CACHING));
2791  19 api.setImplementation(artifact.getAttribute(APIConstants.PROTOTYPE_OVERVIEW_IMPLEMENTATION));
2792  19 api.setVisibility(artifact.getAttribute(APIConstants.API_OVERVIEW_VISIBILITY));
2793   
2794  19 String tenantDomainName = MultitenantUtils.getTenantDomain(replaceEmailDomainBack(providerName));
2795  19 int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager()
2796    .getTenantId(tenantDomainName);
2797   
2798  19 boolean isGlobalThrottlingEnabled = APIUtil.isAdvanceThrottlingEnabled();
2799   
2800  19 if (isGlobalThrottlingEnabled) {
2801  19 String apiLevelTier = ApiMgtDAO.getInstance().getAPILevelTier(apiId);
2802  19 api.setApiLevelPolicy(apiLevelTier);
2803    }
2804   
2805  19 String tiers = artifact.getAttribute(APIConstants.API_OVERVIEW_TIER);
2806  19 Map<String, Tier> definedTiers = getTiers(tenantId);
2807  19 Set<Tier> availableTier = getAvailableTiers(definedTiers, tiers, apiName);
2808  19 api.addAvailableTiers(availableTier);
2809   
2810   
2811  19 api.setContext(artifact.getAttribute(APIConstants.API_OVERVIEW_CONTEXT));
2812  19 api.setContextTemplate(artifact.getAttribute(APIConstants.API_OVERVIEW_CONTEXT_TEMPLATE));
2813  19 api.setLatest(Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_IS_LATEST)));
2814  19 ArrayList<URITemplate> urlPatternsList;
2815   
2816  19 Set<Scope> scopes = ApiMgtDAO.getInstance().getAPIScopes(oldId);
2817  19 api.setScopes(scopes);
2818   
2819  19 HashMap<String, String> resourceScopes;
2820  19 resourceScopes = ApiMgtDAO.getInstance().getResourceToScopeMapping(oldId);
2821   
2822  19 urlPatternsList = ApiMgtDAO.getInstance().getAllURITemplates(oldContext, oldId.getVersion());
2823  19 Set<URITemplate> uriTemplates = new HashSet<URITemplate>(urlPatternsList);
2824   
2825  19 for (URITemplate uriTemplate : uriTemplates) {
2826  18 uriTemplate.setResourceURI(api.getUrl());
2827  18 uriTemplate.setResourceSandboxURI(api.getSandboxUrl());
2828  18 String resourceScopeKey = APIUtil.getResourceKey(oldContext, oldId.getVersion(), uriTemplate.getUriTemplate(), uriTemplate.getHTTPVerb());
2829  18 uriTemplate.setScope(findScopeByKey(scopes, resourceScopes.get(resourceScopeKey)));
2830   
2831    }
2832  19 api.setUriTemplates(uriTemplates);
2833   
2834  19 Set<String> tags = new HashSet<String>();
2835  19 Tag[] tag = registry.getTags(artifactPath);
2836  19 for (Tag tag1 : tag) {
2837  39 tags.add(tag1.getTagName());
2838    }
2839  19 api.addTags(tags);
2840  19 api.setLastUpdated(registry.get(artifactPath).getLastModified());
2841  19 api.setAsDefaultVersion(Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_IS_DEFAULT_VERSION)));
2842   
2843  19 String environments = artifact.getAttribute(APIConstants.API_OVERVIEW_ENVIRONMENTS);
2844  19 api.setEnvironments(extractEnvironmentsForAPI(environments));
2845  19 api.setCorsConfiguration(getCorsConfigurationFromArtifact(artifact));
2846   
2847    } catch (GovernanceException e) {
2848  0 String msg = "Failed to get API fro artifact ";
2849  0 throw new APIManagementException(msg, e);
2850    } catch (RegistryException e) {
2851  0 String msg = "Failed to get LastAccess time or Rating";
2852  0 throw new APIManagementException(msg, e);
2853    } catch (UserStoreException e) {
2854  0 String msg = "Failed to get User Realm of API Provider";
2855  0 throw new APIManagementException(msg, e);
2856    }
2857  19 return api;
2858    }
2859   
 
2860  566 toggle public static boolean checkAccessTokenPartitioningEnabled() {
2861  566 return OAuthServerConfiguration.getInstance().isAccessTokenPartitioningEnabled();
2862    }
2863   
 
2864  0 toggle public static boolean checkUserNameAssertionEnabled() {
2865  0 return OAuthServerConfiguration.getInstance().isUserNameAssertionEnabled();
2866    }
2867   
 
2868  0 toggle public static String[] getAvailableKeyStoreTables() throws APIManagementException {
2869  0 String[] keyStoreTables = new String[0];
2870  0 Map<String, String> domainMappings = getAvailableUserStoreDomainMappings();
2871  0 if (domainMappings != null) {
2872  0 keyStoreTables = new String[domainMappings.size()];
2873  0 int i = 0;
2874  0 for (Entry<String, String> e : domainMappings.entrySet()) {
2875  0 String value = e.getValue();
2876  0 keyStoreTables[i] = APIConstants.ACCESS_TOKEN_STORE_TABLE + "_" + value.trim();
2877  0 i++;
2878    }
2879    }
2880  0 return keyStoreTables;
2881    }
2882   
 
2883  0 toggle public static Map<String, String> getAvailableUserStoreDomainMappings() throws
2884    APIManagementException {
2885  0 Map<String, String> userStoreDomainMap = new HashMap<String, String>();
2886  0 String domainsStr = OAuthServerConfiguration.getInstance().getAccessTokenPartitioningDomains();
2887  0 if (domainsStr != null) {
2888  0 String[] userStoreDomainsArr = domainsStr.split(",");
2889  0 for (String anUserStoreDomainsArr : userStoreDomainsArr) {
2890  0 String[] mapping = anUserStoreDomainsArr.trim().split(":"); //A:foo.com , B:bar.com
2891  0 if (mapping.length < 2) {
2892  0 throw new APIManagementException("Domain mapping has not defined");
2893    }
2894  0 userStoreDomainMap.put(mapping[1].trim(), mapping[0].trim()); //key=domain & value=mapping
2895    }
2896    }
2897  0 return userStoreDomainMap;
2898    }
2899   
 
2900  0 toggle public static String getAccessTokenStoreTableFromUserId(String userId)
2901    throws APIManagementException {
2902  0 String accessTokenStoreTable = APIConstants.ACCESS_TOKEN_STORE_TABLE;
2903  0 String userStore;
2904  0 if (userId != null) {
2905  0 String[] strArr = userId.split("/");
2906  0 if (strArr.length > 1) {
2907  0 userStore = strArr[0];
2908  0 Map<String, String> availableDomainMappings = getAvailableUserStoreDomainMappings();
2909  0 if (availableDomainMappings != null &&
2910    availableDomainMappings.containsKey(userStore)) {
2911  0 accessTokenStoreTable = accessTokenStoreTable + "_" +
2912    availableDomainMappings.get(userStore);
2913    }
2914    }
2915    }
2916  0 return accessTokenStoreTable;
2917    }
2918   
 
2919  0 toggle public static String getAccessTokenStoreTableFromAccessToken(String apiKey)
2920    throws APIManagementException {
2921  0 String userId = getUserIdFromAccessToken(apiKey); //i.e: 'foo.com/admin' or 'admin'
2922  0 return getAccessTokenStoreTableFromUserId(userId);
2923    }
2924   
 
2925  0 toggle public static String getUserIdFromAccessToken(String apiKey) {
2926  0 String userId = null;
2927  0 String decodedKey = new String(Base64.decodeBase64(apiKey.getBytes(Charset.defaultCharset())), Charset.defaultCharset());
2928  0 String[] tmpArr = decodedKey.split(":");
2929  0 if (tmpArr.length == 2) { //tmpArr[0]= userStoreDomain & tmpArr[1] = userId
2930  0 userId = tmpArr[1];
2931    }
2932  0 return userId;
2933    }
2934   
2935    /**
2936    * validates if an accessToken has expired or not
2937    *
2938    * @param accessTokenDO
2939    * @return true if token has expired else false
2940    */
 
2941  91 toggle public static boolean isAccessTokenExpired(APIKeyValidationInfoDTO accessTokenDO) {
2942  91 long validityPeriod = accessTokenDO.getValidityPeriod();
2943  91 long issuedTime = accessTokenDO.getIssuedTime();
2944  91 long timestampSkew = OAuthServerConfiguration.getInstance().getTimeStampSkewInSeconds() * 1000;
2945  91 long currentTime = System.currentTimeMillis();
2946   
2947    //If the validity period is not an never expiring value
2948  91 if (validityPeriod != Long.MAX_VALUE &&
2949    // For cases where validityPeriod is closer to Long.MAX_VALUE (then issuedTime + validityPeriod would spill
2950    // over and would produce a negative value)
2951    (currentTime - timestampSkew) > validityPeriod) {
2952    //check the validity of cached OAuth2AccessToken Response
2953   
2954  91 if ((currentTime - timestampSkew) > (issuedTime + validityPeriod)) {
2955  0 accessTokenDO.setValidationStatus(APIConstants.KeyValidationStatus.API_AUTH_INVALID_CREDENTIALS);
2956  0 return true;
2957    }
2958    }
2959   
2960  91 return false;
2961    }
2962   
2963    /**
2964    * When an input is having '@',replace it with '-AT-' [This is required to persist API data in registry,as registry
2965    * paths don't allow '@' sign.]
2966    *
2967    * @param input inputString
2968    * @return String modifiedString
2969    */
 
2970  3063 toggle public static String replaceEmailDomain(String input) {
2971  3063 if (input != null && input.contains(APIConstants.EMAIL_DOMAIN_SEPARATOR)) {
2972  572 input = input.replace(APIConstants.EMAIL_DOMAIN_SEPARATOR, APIConstants.EMAIL_DOMAIN_SEPARATOR_REPLACEMENT);
2973    }
2974  3063 return input;
2975    }
2976   
2977    /**
2978    * When an input is having '-AT-',replace it with @ [This is required to persist API data between registry and database]
2979    *
2980    * @param input inputString
2981    * @return String modifiedString
2982    */
 
2983  30228 toggle public static String replaceEmailDomainBack(String input) {
2984  30228 if (input != null && input.contains(APIConstants.EMAIL_DOMAIN_SEPARATOR_REPLACEMENT)) {
2985  7737 input = input.replace(APIConstants.EMAIL_DOMAIN_SEPARATOR_REPLACEMENT,
2986    APIConstants.EMAIL_DOMAIN_SEPARATOR);
2987    }
2988  30228 return input;
2989    }
2990   
 
2991  0 toggle public static void copyResourcePermissions(String username, String sourceArtifactPath, String targetArtifactPath)
2992    throws APIManagementException {
2993  0 String sourceResourcePath = RegistryUtils.getAbsolutePath(RegistryContext.getBaseInstance(),
2994    APIUtil.getMountedPath(RegistryContext.getBaseInstance(),
2995    RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH)
2996    + sourceArtifactPath);
2997   
2998  0 String targetResourcePath = RegistryUtils.getAbsolutePath(RegistryContext.getBaseInstance(),
2999    APIUtil.getMountedPath(RegistryContext.getBaseInstance(),
3000    RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH)
3001    + targetArtifactPath);
3002   
3003  0 String tenantDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(username));
3004   
3005  0 try {
3006  0 int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager().getTenantId(tenantDomain);
3007  0 org.wso2.carbon.user.api.AuthorizationManager authManager = ServiceReferenceHolder.getInstance().getRealmService().
3008    getTenantUserRealm(tenantId).getAuthorizationManager();
3009  0 String[] allowedRoles = authManager.getAllowedRolesForResource(sourceResourcePath, ActionConstants.GET);
3010   
3011  0 if (allowedRoles != null) {
3012   
3013  0 for (String allowedRole : allowedRoles) {
3014  0 authManager.authorizeRole(allowedRole, targetResourcePath, ActionConstants.GET);
3015    }
3016    }
3017   
3018    } catch (UserStoreException e) {
3019  0 throw new APIManagementException("Error while adding role permissions to API", e);
3020    }
3021    }
3022   
3023    /**
3024    * This function is to set resource permissions based on its visibility
3025    *
3026    * @param username Username
3027    * @param visibility API visibility
3028    * @param roles Authorized roles
3029    * @param artifactPath API resource path
3030    * @throws APIManagementException Throwing exception
3031    */
 
3032  320 toggle public static void setResourcePermissions(String username, String visibility, String[] roles, String
3033    artifactPath) throws APIManagementException {
3034  320 setResourcePermissions(username, visibility, roles, artifactPath, null);
3035    }
3036   
3037    /**
3038    * This function is to set resource permissions based on its visibility
3039    *
3040    * @param visibility API visibility
3041    * @param roles Authorized roles
3042    * @param artifactPath API resource path
3043    * @param registry Registry
3044    * @throws APIManagementException Throwing exception
3045    */
 
3046  729 toggle public static void setResourcePermissions(String username, String visibility, String[] roles, String
3047    artifactPath, Registry registry) throws APIManagementException {
3048  729 try {
3049  729 String resourcePath = RegistryUtils.getAbsolutePath(RegistryContext.getBaseInstance(),
3050    APIUtil.getMountedPath(RegistryContext.getBaseInstance(),
3051    RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH)
3052    + artifactPath);
3053  729 Resource registryResource = null;
3054   
3055  729 if (registry != null && registry.resourceExists(artifactPath)) {
3056  357 registryResource = registry.get(artifactPath);
3057    }
3058  729 StringBuilder publisherAccessRoles = new StringBuilder(APIConstants.NULL_USER_ROLE_LIST);
3059   
3060  729 if (registryResource != null) {
3061  357 String publisherRole = registryResource.getProperty(APIConstants.PUBLISHER_ROLES);
3062  357 if (publisherRole != null) {
3063  61 publisherAccessRoles = new StringBuilder(publisherRole);
3064    }
3065  357 if (StringUtils.isEmpty(publisherAccessRoles.toString())) {
3066  0 publisherAccessRoles = new StringBuilder(APIConstants.NULL_USER_ROLE_LIST);
3067    }
3068   
3069  357 if (visibility.equalsIgnoreCase(APIConstants.API_GLOBAL_VISIBILITY)) {
3070  324 registryResource.setProperty(APIConstants.STORE_VIEW_ROLES, APIConstants.NULL_USER_ROLE_LIST);
3071  324 publisherAccessRoles = new StringBuilder(APIConstants.NULL_USER_ROLE_LIST); // set publisher
3072    // access roles null since store visibility is global. We do not need to add any roles to
3073    // store_view_role property.
3074    } else {
3075  33 registryResource.setProperty(APIConstants.STORE_VIEW_ROLES, publisherAccessRoles.toString());
3076    }
3077    }
3078  729 String tenantDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(username));
3079  729 if (!org.wso2.carbon.utils.multitenancy.MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
3080  188 int tenantId = ServiceReferenceHolder.getInstance().getRealmService().
3081    getTenantManager().getTenantId(tenantDomain);
3082    // calculate resource path
3083  188 RegistryAuthorizationManager authorizationManager = new RegistryAuthorizationManager
3084    (ServiceReferenceHolder.getUserRealm());
3085  188 resourcePath = authorizationManager.computePathOnMount(resourcePath);
3086  188 org.wso2.carbon.user.api.AuthorizationManager authManager =
3087    ServiceReferenceHolder.getInstance().getRealmService().
3088    getTenantUserRealm(tenantId).getAuthorizationManager();
3089  188 if (visibility != null && APIConstants.API_RESTRICTED_VISIBILITY.equalsIgnoreCase(visibility)) {
3090  13 boolean isRoleEveryOne = false;
3091    /*If no roles have defined, authorize for everyone role */
3092  13 if (roles != null) {
3093  13 if (roles.length == 1 && "".equals(roles[0])) {
3094  0 authManager.authorizeRole(APIConstants.EVERYONE_ROLE, resourcePath, ActionConstants.GET);
3095  0 isRoleEveryOne = true;
3096    } else {
3097  13 for (String role : roles) {
3098  13 if (APIConstants.EVERYONE_ROLE.equalsIgnoreCase(role)) {
3099  0 isRoleEveryOne = true;
3100    }
3101  13 authManager.authorizeRole(role, resourcePath, ActionConstants.GET);
3102  13 publisherAccessRoles.append(",").append(role.toLowerCase());
3103    }
3104    }
3105    }
3106  13 if (!isRoleEveryOne) {
3107  13 authManager.denyRole(APIConstants.EVERYONE_ROLE, resourcePath, ActionConstants.GET);
3108    }
3109  13 authManager.denyRole(APIConstants.ANONYMOUS_ROLE, resourcePath, ActionConstants.GET);
3110  175 } else if (visibility != null && APIConstants.API_PRIVATE_VISIBILITY.equalsIgnoreCase(visibility)) {
3111  2 authManager.authorizeRole(APIConstants.EVERYONE_ROLE, resourcePath, ActionConstants.GET);
3112  2 authManager.denyRole(APIConstants.ANONYMOUS_ROLE, resourcePath, ActionConstants.GET);
3113  173 } else if (visibility != null && APIConstants.DOC_OWNER_VISIBILITY.equalsIgnoreCase(visibility)) {
3114   
3115    /*If no roles have defined, deny access for everyone & anonymous role */
3116  0 if (roles == null) {
3117  0 authManager.denyRole(APIConstants.EVERYONE_ROLE, resourcePath, ActionConstants.GET);
3118  0 authManager.denyRole(APIConstants.ANONYMOUS_ROLE, resourcePath, ActionConstants.GET);
3119    } else {
3120  0 for (String role : roles) {
3121  0 authManager.denyRole(role, resourcePath, ActionConstants.GET);
3122   
3123    }
3124    }
3125    } else {
3126  173 authManager.authorizeRole(APIConstants.EVERYONE_ROLE, resourcePath, ActionConstants.GET);
3127  173 authManager.authorizeRole(APIConstants.ANONYMOUS_ROLE, resourcePath, ActionConstants.GET);
3128    }
3129    } else {
3130  541 RegistryAuthorizationManager authorizationManager = new RegistryAuthorizationManager
3131    (ServiceReferenceHolder.getUserRealm());
3132   
3133  541 if (visibility != null && APIConstants.API_RESTRICTED_VISIBILITY.equalsIgnoreCase(visibility)) {
3134  48 boolean isRoleEveryOne = false;
3135  48 if (roles != null) {
3136  46 for (String role : roles) {
3137  61 if (APIConstants.EVERYONE_ROLE.equalsIgnoreCase(role)) {
3138  0 isRoleEveryOne = true;
3139    }
3140  61 authorizationManager.authorizeRole(role, resourcePath, ActionConstants.GET);
3141  61 publisherAccessRoles.append(",").append(role.toLowerCase());
3142    }
3143    }
3144  48 if (!isRoleEveryOne) {
3145  48 authorizationManager.denyRole(APIConstants.EVERYONE_ROLE, resourcePath, ActionConstants.GET);
3146    }
3147  48 authorizationManager.denyRole(APIConstants.ANONYMOUS_ROLE, resourcePath, ActionConstants.GET);
3148   
3149  493 } else if (visibility != null && APIConstants.API_PRIVATE_VISIBILITY.equalsIgnoreCase(visibility)) {
3150  4 authorizationManager.authorizeRole(APIConstants.EVERYONE_ROLE, resourcePath, ActionConstants.GET);
3151  4 authorizationManager.denyRole(APIConstants.ANONYMOUS_ROLE, resourcePath, ActionConstants.GET);
3152  489 } else if (visibility != null && APIConstants.DOC_OWNER_VISIBILITY.equalsIgnoreCase(visibility)) {
3153    /*If no roles have defined, deny access for everyone & anonymous role */
3154  0 if (roles == null) {
3155  0 authorizationManager.denyRole(APIConstants.EVERYONE_ROLE, resourcePath, ActionConstants.GET);
3156  0 authorizationManager.denyRole(APIConstants.ANONYMOUS_ROLE, resourcePath, ActionConstants.GET);
3157    } else {
3158  0 for (String role : roles) {
3159  0 authorizationManager.denyRole(role, resourcePath, ActionConstants.GET);
3160   
3161    }
3162    }
3163    } else {
3164  489 authorizationManager.authorizeRole(APIConstants.EVERYONE_ROLE, resourcePath, ActionConstants.GET);
3165  489 authorizationManager.authorizeRole(APIConstants.ANONYMOUS_ROLE, resourcePath, ActionConstants.GET);
3166    }
3167    }
3168  729 if (registryResource != null) {
3169  357 registryResource.setProperty(APIConstants.STORE_VIEW_ROLES, publisherAccessRoles.toString());
3170  357 registry.put(artifactPath, registryResource);
3171    }
3172   
3173    } catch (UserStoreException e) {
3174  0 throw new APIManagementException("Error while adding role permissions to API", e);
3175    } catch (RegistryException e) {
3176  0 throw new APIManagementException("Registry exception while adding role permissions to API", e);
3177    }
3178    }
3179   
3180    /**
3181    * This function is to set resource permissions based on its visibility
3182    *
3183    * @param artifactPath API resource path
3184    * @throws APIManagementException Throwing exception
3185    */
 
3186  360 toggle public static void clearResourcePermissions(String artifactPath, APIIdentifier apiId, int tenantId)
3187    throws APIManagementException {
3188  360 try {
3189  360 String resourcePath = RegistryUtils.getAbsolutePath(RegistryContext.getBaseInstance(),
3190    APIUtil.getMountedPath(RegistryContext.getBaseInstance(),
3191    RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH) + artifactPath);
3192  360 String tenantDomain = MultitenantUtils
3193    .getTenantDomain(APIUtil.replaceEmailDomainBack(apiId.getProviderName()));
3194  360 if (!org.wso2.carbon.utils.multitenancy.MultitenantConstants.SUPER_TENANT_DOMAIN_NAME
3195    .equals(tenantDomain)) {
3196  89 org.wso2.carbon.user.api.AuthorizationManager authManager = ServiceReferenceHolder.getInstance()
3197    .getRealmService().getTenantUserRealm(tenantId).getAuthorizationManager();
3198  89 authManager.clearResourceAuthorizations(resourcePath);
3199    } else {
3200  271 RegistryAuthorizationManager authorizationManager = new RegistryAuthorizationManager(
3201    ServiceReferenceHolder.getUserRealm());
3202  271 authorizationManager.clearResourceAuthorizations(resourcePath);
3203    }
3204    } catch (UserStoreException e) {
3205  0 handleException("Error while adding role permissions to API", e);
3206    }
3207    }
3208   
 
3209  107 toggle public static void loadTenantAPIPolicy(String tenant, int tenantID) throws APIManagementException {
3210   
3211  107 String tierBasePath = CarbonUtils.getCarbonHome() + File.separator + "repository" + File.separator + "resources"
3212    + File.separator + "default-tiers" + File.separator;
3213   
3214  107 String apiTierFilePath = tierBasePath + APIConstants.DEFAULT_API_TIER_FILE_NAME;
3215  107 String appTierFilePath = tierBasePath + APIConstants.DEFAULT_APP_TIER_FILE_NAME;
3216  107 String resTierFilePath = tierBasePath + APIConstants.DEFAULT_RES_TIER_FILE_NAME;
3217   
3218  107 loadTenantAPIPolicy(tenantID, APIConstants.API_TIER_LOCATION, apiTierFilePath);
3219  107 loadTenantAPIPolicy(tenantID, APIConstants.APP_TIER_LOCATION, appTierFilePath);
3220  107 loadTenantAPIPolicy(tenantID, APIConstants.RES_TIER_LOCATION, resTierFilePath);
3221    }
3222   
3223    /**
3224    * Load the throttling policy to the registry for tenants
3225    *
3226    * @param tenantID
3227    * @param location
3228    * @param fileName
3229    * @throws APIManagementException
3230    */
 
3231  321 toggle private static void loadTenantAPIPolicy(int tenantID, String location, String fileName)
3232    throws APIManagementException {
3233  321 InputStream inputStream = null;
3234   
3235  321 try {
3236  321 RegistryService registryService = ServiceReferenceHolder.getInstance().getRegistryService();
3237   
3238  321 UserRegistry govRegistry = registryService.getGovernanceSystemRegistry(tenantID);
3239   
3240  321 if (govRegistry.resourceExists(location)) {
3241  306 if (log.isDebugEnabled()) {
3242  36 log.debug("Tier policies already uploaded to the tenant's registry space");
3243    }
3244  306 return;
3245    }
3246  15 if (log.isDebugEnabled()) {
3247  0 log.debug("Adding API tier policies to the tenant's registry");
3248    }
3249  15 File defaultTiers = new File(fileName);
3250  15 if (!defaultTiers.exists()) {
3251  0 log.info("Default tier policies not found in : " + fileName);
3252  0 return;
3253    }
3254  15 inputStream = FileUtils.openInputStream(defaultTiers);
3255  15 byte[] data = IOUtils.toByteArray(inputStream);
3256  15 Resource resource = govRegistry.newResource();
3257  15 resource.setContent(data);
3258  15 govRegistry.put(location, resource);
3259   
3260    } catch (RegistryException e) {
3261  0 throw new APIManagementException("Error while saving policy information to the registry", e);
3262    } catch (IOException e) {
3263  0 throw new APIManagementException("Error while reading policy file content", e);
3264    } finally {
3265  321 if (inputStream != null) {
3266  15 try {
3267  15 inputStream.close();
3268    } catch (IOException e) {
3269  0 log.error("Error when closing input stream", e);
3270    }
3271    }
3272    }
3273    }
3274   
3275    /**
3276    * Load the External API Store Configuration to the registry
3277    *
3278    * @param tenantID
3279    * @throws org.wso2.carbon.apimgt.api.APIManagementException
3280    */
3281   
 
3282  35 toggle public static void loadTenantExternalStoreConfig(int tenantID) throws APIManagementException {
3283  35 try {
3284  35 RegistryService registryService = ServiceReferenceHolder.getInstance().getRegistryService();
3285   
3286  35 UserRegistry govRegistry = registryService.getGovernanceSystemRegistry(tenantID);
3287   
3288  35 if (govRegistry.resourceExists(APIConstants.EXTERNAL_API_STORES_LOCATION)) {
3289  30 log.debug("External Stores configuration already uploaded to the registry");
3290  30 return;
3291    }
3292  5 if (log.isDebugEnabled()) {
3293  0 log.debug("Adding External Stores configuration to the tenant's registry");
3294    }
3295  5 InputStream inputStream =
3296    APIManagerComponent.class.getResourceAsStream("/externalstores/default-external-api-stores.xml");
3297  5 byte[] data = IOUtils.toByteArray(inputStream);
3298  5 Resource resource = govRegistry.newResource();
3299  5 resource.setContent(data);
3300  5 govRegistry.put(APIConstants.EXTERNAL_API_STORES_LOCATION, resource);
3301   
3302    /*set resource permission*/
3303  5 org.wso2.carbon.user.api.AuthorizationManager authManager =
3304    ServiceReferenceHolder.getInstance().getRealmService().getTenantUserRealm(tenantID).
3305    getAuthorizationManager();
3306  5 String resourcePath = RegistryUtils.getAbsolutePath(RegistryContext.getBaseInstance(),
3307    APIUtil.getMountedPath(RegistryContext.getBaseInstance(), RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH)
3308    + APIConstants.EXTERNAL_API_STORES_LOCATION);
3309  5 authManager.denyRole(APIConstants.EVERYONE_ROLE, resourcePath, ActionConstants.GET);
3310   
3311    } catch (RegistryException e) {
3312  0 throw new APIManagementException("Error while saving External Stores configuration information to the " +
3313    "registry", e);
3314    } catch (IOException e) {
3315  0 throw new APIManagementException("Error while reading External Stores configuration file content", e);
3316    } catch (UserStoreException e) {
3317  0 throw new APIManagementException("Error while setting permission to External Stores configuration file", e);
3318    }
3319    }
3320   
3321    /**
3322    * Load the Google Analytics Configuration to the registry
3323    *
3324    * @param tenantID
3325    * @throws APIManagementException
3326    */
3327   
 
3328  35 toggle public static void loadTenantGAConfig(int tenantID) throws APIManagementException {
3329  35 InputStream inputStream = null;
3330  35 try {
3331  35 RegistryService registryService =
3332    ServiceReferenceHolder.getInstance()
3333    .getRegistryService();
3334   
3335  35 UserRegistry govRegistry = registryService.getGovernanceSystemRegistry(tenantID);
3336   
3337  35 if (govRegistry.resourceExists(APIConstants.GA_CONFIGURATION_LOCATION)) {
3338  30 log.debug("Google Analytics configuration already uploaded to the registry");
3339  30 return;
3340    }
3341  5 if (log.isDebugEnabled()) {
3342  0 log.debug("Adding Google Analytics configuration to the tenant's registry");
3343    }
3344  5 inputStream = APIManagerComponent.class.getResourceAsStream("/statistics/default-ga-config.xml");
3345  5 byte[] data = IOUtils.toByteArray(inputStream);
3346  5 Resource resource = govRegistry.newResource();
3347  5 resource.setContent(data);
3348  5 govRegistry.put(APIConstants.GA_CONFIGURATION_LOCATION, resource);
3349   
3350    /*set resource permission*/
3351  5 org.wso2.carbon.user.api.AuthorizationManager authManager =
3352    ServiceReferenceHolder.getInstance().getRealmService().
3353    getTenantUserRealm(tenantID).getAuthorizationManager();
3354  5 String resourcePath = RegistryUtils.getAbsolutePath(RegistryContext.getBaseInstance(),
3355    APIUtil.getMountedPath(RegistryContext.getBaseInstance(),
3356    RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH) + APIConstants.GA_CONFIGURATION_LOCATION);
3357  5 authManager.denyRole(APIConstants.EVERYONE_ROLE, resourcePath, ActionConstants.GET);
3358   
3359    } catch (RegistryException e) {
3360  0 throw new APIManagementException("Error while saving Google Analytics configuration information to the registry", e);
3361    } catch (IOException e) {
3362  0 throw new APIManagementException("Error while reading Google Analytics configuration file content", e);
3363    } catch (UserStoreException e) {
3364  0 throw new APIManagementException("Error while setting permission to Google Analytics configuration file", e);
3365    } finally {
3366  35 try {
3367  35 if (inputStream != null) {
3368  5 inputStream.close();
3369    }
3370    } catch (IOException e) {
3371  0 if (log.isWarnEnabled()) {
3372  0 log.warn("Error while closing the input stream", e);
3373    }
3374    }
3375    }
3376    }
3377   
 
3378  35 toggle public static void loadTenantWorkFlowExtensions(int tenantID)
3379    throws APIManagementException {
3380    // TODO: Merge different resource loading methods and create a single method.
3381  35 try {
3382  35 RegistryService registryService = ServiceReferenceHolder.getInstance().getRegistryService();
3383   
3384  35 UserRegistry govRegistry = registryService.getGovernanceSystemRegistry(tenantID);
3385   
3386  35 if (govRegistry.resourceExists(APIConstants.WORKFLOW_EXECUTOR_LOCATION)) {
3387  30 log.debug("External Stores configuration already uploaded to the registry");
3388  30 return;
3389    }
3390  5 if (log.isDebugEnabled()) {
3391  0 log.debug("Adding External Stores configuration to the tenant's registry");
3392    }
3393  5 InputStream inputStream =
3394    APIManagerComponent.class.getResourceAsStream("/workflowextensions/default-workflow-extensions.xml");
3395  5 byte[] data = IOUtils.toByteArray(inputStream);
3396  5 Resource resource = govRegistry.newResource();
3397  5 resource.setContent(data);
3398  5 resource.setMediaType(APIConstants.WORKFLOW_MEDIA_TYPE);
3399  5 govRegistry.put(APIConstants.WORKFLOW_EXECUTOR_LOCATION, resource);
3400   
3401    } catch (RegistryException e) {
3402  0 throw new APIManagementException("Error while saving External Stores configuration information to the registry", e);
3403    } catch (IOException e) {
3404  0 throw new APIManagementException("Error while reading External Stores configuration file content", e);
3405    }
3406    }
3407   
3408    /**
3409    * @param tenantId
3410    * @throws APIManagementException
3411    */
 
3412  35 toggle public static void loadTenantSelfSignUpConfigurations(int tenantId)
3413    throws APIManagementException {
3414  35 try {
3415  35 RegistryService registryService = ServiceReferenceHolder.getInstance().getRegistryService();
3416  35 UserRegistry govRegistry = registryService.getGovernanceSystemRegistry(tenantId);
3417   
3418  35 if (govRegistry.resourceExists(APIConstants.SELF_SIGN_UP_CONFIG_LOCATION)) {
3419  30 log.debug("Self signup configuration already uploaded to the registry");
3420  30 return;
3421    }
3422  5 if (log.isDebugEnabled()) {
3423  0 log.debug("Adding Self signup configuration to the tenant's registry");
3424    }
3425  5 InputStream inputStream;
3426  5 if (tenantId == org.wso2.carbon.utils.multitenancy.MultitenantConstants.SUPER_TENANT_ID) {
3427  0 inputStream =
3428    APIManagerComponent.class.getResourceAsStream("/signupconfigurations/default-sign-up-config.xml");
3429    } else {
3430  5 inputStream =
3431    APIManagerComponent.class.getResourceAsStream("/signupconfigurations/tenant-sign-up-config.xml");
3432    }
3433  5 byte[] data = IOUtils.toByteArray(inputStream);
3434  5 Resource resource = govRegistry.newResource();
3435  5 resource.setContent(data);
3436  5 resource.setMediaType(APIConstants.SELF_SIGN_UP_CONFIG_MEDIA_TYPE);
3437  5 govRegistry.put(APIConstants.SELF_SIGN_UP_CONFIG_LOCATION, resource);
3438   
3439    } catch (RegistryException e) {
3440  0 throw new APIManagementException("Error while saving Self signup configuration information to the registry", e);
3441    } catch (IOException e) {
3442  0 throw new APIManagementException("Error while reading Self signup configuration file content", e);
3443    }
3444    }
3445   
 
3446  156 toggle public static void loadTenantConf(int tenantID) throws APIManagementException {
3447  156 RegistryService registryService = ServiceReferenceHolder.getInstance().getRegistryService();
3448  156 try {
3449  156 UserRegistry registry = registryService.getConfigSystemRegistry(tenantID);
3450  156 if (registry.resourceExists(APIConstants.API_TENANT_CONF_LOCATION)) {
3451  151 log.debug("Tenant conf already uploaded to the registry");
3452  151 return;
3453    }
3454   
3455  5 String tenantConfLocation = CarbonUtils.getCarbonHome() + File.separator +
3456    APIConstants.RESOURCE_FOLDER_LOCATION + File.separator +
3457    APIConstants.API_TENANT_CONF;
3458   
3459  5 File tenantConfFile = new File(tenantConfLocation);
3460   
3461  5 byte[] data;
3462   
3463  5 if (tenantConfFile.exists()) { // Load conf from resources directory in pack if it exists
3464  5 FileInputStream fileInputStream = new FileInputStream(tenantConfFile);
3465  5 data = IOUtils.toByteArray(fileInputStream);
3466    } else { // Fallback to loading the conf that is stored at jar level if file does not exist in pack
3467  0 InputStream inputStream = APIManagerComponent.class.getResourceAsStream("/tenant/" + APIConstants.API_TENANT_CONF);
3468  0 data = IOUtils.toByteArray(inputStream);
3469    }
3470   
3471  5 log.debug("Adding tenant config to the registry");
3472  5 Resource resource = registry.newResource();
3473  5 resource.setMediaType(APIConstants.APPLICATION_JSON_MEDIA_TYPE);
3474  5 resource.setContent(data);
3475   
3476  5 registry.put(APIConstants.API_TENANT_CONF_LOCATION, resource);
3477    } catch (RegistryException e) {
3478  0 throw new APIManagementException("Error while saving tenant conf to the registry", e);
3479    } catch (IOException e) {
3480  0 throw new APIManagementException("Error while reading tenant conf file content", e);
3481    }
3482    }
3483   
3484    /**
3485    * @param tenantId
3486    * @throws APIManagementException
3487    */
 
3488  52 toggle public static void createSelfSignUpRoles(int tenantId) throws APIManagementException {
3489  52 try {
3490  52 RegistryService registryService = ServiceReferenceHolder.getInstance().getRegistryService();
3491  52 UserRegistry govRegistry = registryService.getGovernanceSystemRegistry(tenantId);
3492  52 if (govRegistry.resourceExists(APIConstants.SELF_SIGN_UP_CONFIG_LOCATION)) {
3493  48 Resource resource = govRegistry.get(APIConstants.SELF_SIGN_UP_CONFIG_LOCATION);
3494  48 InputStream content = resource.getContentStream();
3495  48 DocumentBuilderFactory factory = getSecuredDocumentBuilder();
3496  48 factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
3497  48 DocumentBuilder parser = factory.newDocumentBuilder();
3498  48 Document dc = parser.parse(content);
3499  48 boolean enableSubscriberRoleCreation = isSubscriberRoleCreationEnabled(tenantId);
3500  48 String signUpDomain = dc.getElementsByTagName(APIConstants.SELF_SIGN_UP_REG_DOMAIN_ELEM).item(0)
3501    .getFirstChild().getNodeValue();
3502   
3503  48 if (enableSubscriberRoleCreation) {
3504  48 int roleLength = dc.getElementsByTagName(APIConstants.SELF_SIGN_UP_REG_ROLE_NAME_ELEMENT)
3505    .getLength();
3506   
3507  96 for (int i = 0; i < roleLength; i++) {
3508  48 String roleName = dc.getElementsByTagName(APIConstants.SELF_SIGN_UP_REG_ROLE_NAME_ELEMENT)
3509    .item(i).getFirstChild().getNodeValue();
3510  48 boolean isExternalRole = Boolean.parseBoolean(dc
3511    .getElementsByTagName(APIConstants.SELF_SIGN_UP_REG_ROLE_IS_EXTERNAL).item(i)
3512    .getFirstChild().getNodeValue());
3513  48 if (roleName != null) {
3514    // If isExternalRole==false ;create the subscriber role as an internal role
3515  48 if (isExternalRole && signUpDomain != null) {
3516  0 roleName = signUpDomain.toUpperCase() + CarbonConstants.DOMAIN_SEPARATOR + roleName;
3517    } else {
3518  48 roleName = UserCoreConstants.INTERNAL_DOMAIN + CarbonConstants.DOMAIN_SEPARATOR
3519    + roleName;
3520    }
3521  48 createSubscriberRole(roleName, tenantId);
3522    }
3523    }
3524    }
3525    }
3526  52 if (log.isDebugEnabled()) {
3527  6 log.debug("Adding Self signup configuration to the tenant's registry");
3528    }
3529   
3530    } catch (RegistryException e) {
3531  0 throw new APIManagementException("Error while getting Self signup role information from the registry", e);
3532    } catch (ParserConfigurationException e) {
3533  0 throw new APIManagementException("Error while getting Self signup role information from the registry", e);
3534    } catch (SAXException e) {
3535  0 throw new APIManagementException("Error while getting Self signup role information from the registry", e);
3536    } catch (IOException e) {
3537  0 throw new APIManagementException("Error while getting Self signup role information from the registry", e);
3538    }
3539    }
3540   
3541    /**
3542    * Returns whether subscriber role creation enabled for the given tenant in tenant-conf.json
3543    *
3544    * @param tenantId id of the tenant
3545    * @return true if subscriber role creation enabled in tenant-conf.json
3546    */
 
3547  48 toggle public static boolean isSubscriberRoleCreationEnabled(int tenantId) throws APIManagementException {
3548  48 String tenantDomain = getTenantDomainFromTenantId(tenantId);
3549  48 JSONObject defaultRoles = getTenantDefaultRoles(tenantDomain);
3550  48 boolean isSubscriberRoleCreationEnabled = false;
3551  48 if (defaultRoles != null) {
3552  48 JSONObject subscriberRoleConfig = (JSONObject) defaultRoles
3553    .get(APIConstants.API_TENANT_CONF_DEFAULT_ROLES_SUBSCRIBER_ROLE);
3554  48 isSubscriberRoleCreationEnabled = isRoleCreationEnabled(subscriberRoleConfig);
3555    }
3556  48 return isSubscriberRoleCreationEnabled;
3557    }
3558   
3559    /**
3560    * Create default roles specified in APIM per-tenant configuration file
3561    *
3562    * @param tenantId id of the tenant
3563    * @throws APIManagementException
3564    */
 
3565  35 toggle public static void createDefaultRoles(int tenantId) throws APIManagementException {
3566  35 String tenantDomain = getTenantDomainFromTenantId(tenantId);
3567  35 JSONObject defaultRoles = getTenantDefaultRoles(tenantDomain);
3568   
3569  35 if (defaultRoles != null) {
3570    // create publisher role if it's creation is enabled in tenant-conf.json
3571  35 JSONObject publisherRoleConfig = (JSONObject) defaultRoles
3572    .get(APIConstants.API_TENANT_CONF_DEFAULT_ROLES_PUBLISHER_ROLE);
3573  35 if (isRoleCreationEnabled(publisherRoleConfig)) {
3574  35 String publisherRoleName = String.valueOf(publisherRoleConfig
3575    .get(APIConstants.API_TENANT_CONF_DEFAULT_ROLES_ROLENAME));
3576  35 if (!StringUtils.isBlank(publisherRoleName)) {
3577  35 createPublisherRole(publisherRoleName, tenantId);
3578    }
3579    }
3580   
3581    // create creator role if it's creation is enabled in tenant-conf.json
3582  35 JSONObject creatorRoleConfig = (JSONObject) defaultRoles
3583    .get(APIConstants.API_TENANT_CONF_DEFAULT_ROLES_CREATOR_ROLE);
3584  35 if (isRoleCreationEnabled(creatorRoleConfig)) {
3585  35 String creatorRoleName = String.valueOf(creatorRoleConfig
3586    .get(APIConstants.API_TENANT_CONF_DEFAULT_ROLES_ROLENAME));
3587  35 if (!StringUtils.isBlank(creatorRoleName)) {
3588  35 createCreatorRole(creatorRoleName, tenantId);
3589    }
3590    }
3591   
3592  35 createSelfSignUpRoles(tenantId);
3593    }
3594    }
3595   
3596    /**
3597    * Returns whether role creation enabled for the provided role config
3598    *
3599    * @param roleConfig role config in tenat-conf.json
3600    * @return true if role creation enabled for the provided role config
3601    */
 
3602  118 toggle private static boolean isRoleCreationEnabled(JSONObject roleConfig) {
3603  118 boolean roleCreationEnabled = false;
3604  118 if (roleConfig != null && roleConfig.get(
3605    APIConstants.API_TENANT_CONF_DEFAULT_ROLES_CREATE_ON_TENANT_LOAD) != null && (Boolean) (roleConfig.get(
3606    APIConstants.API_TENANT_CONF_DEFAULT_ROLES_CREATE_ON_TENANT_LOAD))) {
3607  118 roleCreationEnabled = true;
3608    }
3609  118 return roleCreationEnabled;
3610    }
3611   
 
3612  2153 toggle public static boolean isAnalyticsEnabled() {
3613  2153 return APIManagerAnalyticsConfiguration.getInstance().isAnalyticsEnabled();
3614    }
3615   
3616    /**
3617    * Returns whether API Publisher Access Control is enabled or not
3618    *
3619    * @return true if publisher access control enabled
3620    */
 
3621  66 toggle public static boolean isAccessControlEnabled() {
3622  66 boolean accessControlEnabled = false;
3623  66 APIManagerConfiguration config = ServiceReferenceHolder.getInstance().
3624    getAPIManagerConfigurationService().getAPIManagerConfiguration();
3625  66 if (config.getFirstProperty(APIConstants.API_PUBLISHER_ENABLE_ACCESS_CONTROL_LEVELS) != null && config.getFirstProperty(APIConstants.API_PUBLISHER_ENABLE_ACCESS_CONTROL_LEVELS).equals("true")) {
3626  64 accessControlEnabled = true;
3627    }
3628  66 return accessControlEnabled;
3629    }
3630   
3631    /**
3632    * Add all the custom sequences of given type to registry
3633    *
3634    * @param registry Registry instance
3635    * @param customSequenceType Custom sequence type which is in/out or fault
3636    * @throws APIManagementException
3637    */
 
3638  426 toggle public static void addDefinedAllSequencesToRegistry(UserRegistry registry,
3639    String customSequenceType)
3640    throws APIManagementException {
3641   
3642  426 InputStream inSeqStream = null;
3643  426 String seqFolderLocation =
3644    APIConstants.API_CUSTOM_SEQUENCES_FOLDER_LOCATION + File.separator +
3645    customSequenceType;
3646   
3647  426 try {
3648  426 File inSequenceDir = new File(seqFolderLocation);
3649  426 File[] sequences;
3650  426 sequences = inSequenceDir.listFiles();
3651   
3652  426 if (sequences != null) {
3653    //Tracks whether new sequences are there to deploy
3654  426 boolean availableNewSequences = false;
3655    //Tracks whether json_fault.xml is in the registry
3656  426 boolean jsonFaultSeqInRegistry = false;
3657   
3658  426 for (File sequenceFile : sequences) {
3659  2130 String sequenceFileName = sequenceFile.getName();
3660  2130 String regResourcePath =
3661    APIConstants.API_CUSTOM_SEQUENCE_LOCATION + '/' +
3662    customSequenceType + '/' + sequenceFileName;
3663  2130 if (registry.resourceExists(regResourcePath)) {
3664  2055 if (APIConstants.API_CUSTOM_SEQ_JSON_FAULT.equals(sequenceFileName)) {
3665  137 jsonFaultSeqInRegistry = true;
3666    }
3667  2055 if (log.isDebugEnabled()) {
3668  240 log.debug("The sequence file with the name " + sequenceFileName
3669    + " already exists in the registry path " + regResourcePath);
3670    }
3671    } else {
3672  75 availableNewSequences = true;
3673  75 if (log.isDebugEnabled()) {
3674  0 log.debug(
3675    "Adding sequence file with the name " + sequenceFileName + " to the registry path "
3676    + regResourcePath);
3677    }
3678   
3679  75 inSeqStream = new FileInputStream(sequenceFile);
3680  75 byte[] inSeqData = IOUtils.toByteArray(inSeqStream);
3681  75 Resource inSeqResource = registry.newResource();
3682  75 inSeqResource.setContent(inSeqData);
3683   
3684  75 registry.put(regResourcePath, inSeqResource);
3685    }
3686   
3687    }
3688    //On the fly migration of json_fault.xml for 2.0.0 to 2.1.0
3689  426 if (APIConstants.API_CUSTOM_SEQUENCE_TYPE_FAULT.equals(customSequenceType) &&
3690    availableNewSequences && jsonFaultSeqInRegistry) {
3691  0 String oldFaultStatHandler = "org.wso2.carbon.apimgt.usage.publisher.APIMgtFaultHandler";
3692  0 String newFaultStatHandler = "org.wso2.carbon.apimgt.gateway.handlers.analytics.APIMgtFaultHandler";
3693  0 String regResourcePath =
3694    APIConstants.API_CUSTOM_SEQUENCE_LOCATION + '/' +
3695    customSequenceType + '/' + APIConstants.API_CUSTOM_SEQ_JSON_FAULT;
3696  0 Resource jsonFaultSeqResource = registry.get(regResourcePath);
3697  0 String oldJsonFaultSeqContent = new String((byte[]) jsonFaultSeqResource.getContent(),
3698    Charset.defaultCharset());
3699  0 if (oldJsonFaultSeqContent != null && oldJsonFaultSeqContent.contains(oldFaultStatHandler)) {
3700  0 String newJsonFaultContent =
3701    oldJsonFaultSeqContent.replace(oldFaultStatHandler, newFaultStatHandler);
3702  0 jsonFaultSeqResource.setContent(newJsonFaultContent);
3703  0 registry.put(regResourcePath, jsonFaultSeqResource);
3704    }
3705   
3706    }
3707    } else {
3708  0 log.error(
3709    "Custom sequence template location unavailable for custom sequence type " +
3710    customSequenceType + " : " + seqFolderLocation
3711    );
3712    }
3713   
3714    } catch (RegistryException e) {
3715  0 throw new APIManagementException(
3716    "Error while saving defined sequences to the registry ", e);
3717    } catch (IOException e) {
3718  0 throw new APIManagementException("Error while reading defined sequence ", e);
3719    } finally {
3720  426 IOUtils.closeQuietly(inSeqStream);
3721    }
3722   
3723    }
3724   
3725    /**
3726    * Adds the sequences defined in repository/resources/customsequences folder to tenant registry
3727    *
3728    * @param tenantID tenant Id
3729    * @throws APIManagementException
3730    */
 
3731  124 toggle public static void writeDefinedSequencesToTenantRegistry(int tenantID)
3732    throws APIManagementException {
3733  124 try {
3734   
3735  124 RegistryService registryService = ServiceReferenceHolder.getInstance().getRegistryService();
3736  124 UserRegistry govRegistry = registryService.getGovernanceSystemRegistry(tenantID);
3737   
3738    //Add all custom in,out and fault sequences to tenant registry
3739  124 APIUtil.addDefinedAllSequencesToRegistry(govRegistry, APIConstants.API_CUSTOM_SEQUENCE_TYPE_IN);
3740  124 APIUtil.addDefinedAllSequencesToRegistry(govRegistry, APIConstants.API_CUSTOM_SEQUENCE_TYPE_OUT);
3741  124 APIUtil.addDefinedAllSequencesToRegistry(govRegistry, APIConstants.API_CUSTOM_SEQUENCE_TYPE_FAULT);
3742   
3743    } catch (RegistryException e) {
3744  0 throw new APIManagementException(
3745    "Error while saving defined sequences to the registry of tenant with id " + tenantID, e);
3746    }
3747    }
3748   
3749    /**
3750    * Load the API RXT to the registry for tenants
3751    *
3752    * @param tenant
3753    * @param tenantID
3754    * @throws APIManagementException
3755    */
3756   
 
3757  107 toggle public static void loadloadTenantAPIRXT(String tenant, int tenantID) throws APIManagementException {
3758  107 RegistryService registryService = ServiceReferenceHolder.getInstance().getRegistryService();
3759  107 UserRegistry registry = null;
3760  107 try {
3761   
3762  107 registry = registryService.getGovernanceSystemRegistry(tenantID);
3763    } catch (RegistryException e) {
3764  0 throw new APIManagementException("Error when create registry instance ", e);
3765    }
3766   
3767  107 String rxtDir = CarbonUtils.getCarbonHome() + File.separator + "repository" + File.separator + "resources" +
3768    File.separator + "rxts";
3769  107 File file = new File(rxtDir);
3770  107 FilenameFilter filenameFilter = new FilenameFilter() {
 
3771  428 toggle @Override
3772    public boolean accept(File dir, String name) {
3773    // if the file extension is .rxt return true, else false
3774  428 return name.endsWith(".rxt");
3775    }
3776    };
3777  107 String[] rxtFilePaths = file.list(filenameFilter);
3778   
3779  107 if (rxtFilePaths == null) {
3780  0 throw new APIManagementException("rxt files not found in directory " + rxtDir);
3781    }
3782   
3783  107 for (String rxtPath : rxtFilePaths) {
3784  321 String resourcePath = GovernanceConstants.RXT_CONFIGS_PATH + RegistryConstants.PATH_SEPARATOR + rxtPath;
3785   
3786    //This is "registry" is a governance registry instance, therefore calculate the relative path to governance.
3787  321 String govRelativePath = RegistryUtils.getRelativePathToOriginal(resourcePath,
3788    APIUtil.getMountedPath(RegistryContext.getBaseInstance(),
3789    RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH));
3790  321 try {
3791    // calculate resource path
3792  321 RegistryAuthorizationManager authorizationManager = new RegistryAuthorizationManager
3793    (ServiceReferenceHolder.getUserRealm());
3794  321 resourcePath = authorizationManager.computePathOnMount(resourcePath);
3795   
3796  321 org.wso2.carbon.user.api.AuthorizationManager authManager = ServiceReferenceHolder.getInstance().getRealmService().
3797    getTenantUserRealm(tenantID).getAuthorizationManager();
3798   
3799  321 if (registry.resourceExists(govRelativePath)) {
3800    // set anonymous user permission to RXTs
3801  321 authManager.authorizeRole(APIConstants.ANONYMOUS_ROLE, resourcePath, ActionConstants.GET);
3802  321 continue;
3803    }
3804   
3805  0 String rxt = FileUtil.readFileToString(rxtDir + File.separator + rxtPath);
3806  0 Resource resource = registry.newResource();
3807  0 resource.setContent(rxt.getBytes(Charset.defaultCharset()));
3808  0 resource.setMediaType(APIConstants.RXT_MEDIA_TYPE);
3809  0 registry.put(govRelativePath, resource);
3810   
3811   
3812  0 authManager.authorizeRole(APIConstants.ANONYMOUS_ROLE, resourcePath, ActionConstants.GET);
3813   
3814    } catch (UserStoreException e) {
3815  0 throw new APIManagementException("Error while adding role permissions to API", e);
3816    } catch (IOException e) {
3817  0 String msg = "Failed to read rxt files";
3818  0 throw new APIManagementException(msg, e);
3819    } catch (RegistryException e) {
3820  0 String msg = "Failed to add rxt to registry ";
3821  0 throw new APIManagementException(msg, e);
3822    }
3823    }
3824   
3825    }
3826   
3827    /**
3828    * Converting the user store domain name to uppercase.
3829    *
3830    * @param username Username to be modified
3831    * @return Username with domain name set to uppercase.
3832    */
 
3833  717 toggle public static String setDomainNameToUppercase(String username) {
3834  717 String modifiedName = username;
3835  717 if (username != null) {
3836  717 String[] nameParts = username.split(CarbonConstants.DOMAIN_SEPARATOR);
3837  717 if (nameParts.length > 1) {
3838  0 modifiedName = nameParts[0].toUpperCase() + CarbonConstants.DOMAIN_SEPARATOR + nameParts[1];
3839    }
3840    }
3841   
3842  717 return modifiedName;
3843    }
3844   
3845    /**
3846    * Create APIM Subscriber role with the given name in specified tenant
3847    *
3848    * @param roleName role name
3849    * @param tenantId id of the tenant
3850    * @throws APIManagementException
3851    */
 
3852  48 toggle public static void createSubscriberRole(String roleName, int tenantId) throws APIManagementException {
3853  48 Permission[] subscriberPermissions = new Permission[]{
3854    new Permission(APIConstants.Permissions.LOGIN, UserMgtConstants.EXECUTE_ACTION),
3855    new Permission(APIConstants.Permissions.API_SUBSCRIBE, UserMgtConstants.EXECUTE_ACTION)};
3856  48 createRole(roleName, subscriberPermissions, tenantId);
3857    }
3858   
3859    /**
3860    * Create APIM Publisher roles with the given name in specified tenant
3861    *
3862    * @param roleName role name
3863    * @param tenantId id of the tenant
3864    * @throws APIManagementException
3865    */
 
3866  35 toggle public static void createPublisherRole(String roleName, int tenantId) throws APIManagementException {
3867  35 Permission[] publisherPermissions = new Permission[]{
3868    new Permission(APIConstants.Permissions.LOGIN, UserMgtConstants.EXECUTE_ACTION),
3869    new Permission(APIConstants.Permissions.API_PUBLISH, UserMgtConstants.EXECUTE_ACTION)};
3870  35 createRole(roleName, publisherPermissions, tenantId);
3871    }
3872   
3873    /**
3874    * Create APIM Creator roles with the given name in specified tenant
3875    *
3876    * @param roleName role name
3877    * @param tenantId id of the tenant
3878    * @throws APIManagementException
3879    */
 
3880  35 toggle public static void createCreatorRole(String roleName, int tenantId) throws APIManagementException {
3881  35 Permission[] creatorPermissions = new Permission[]{
3882    new Permission(APIConstants.Permissions.LOGIN, UserMgtConstants.EXECUTE_ACTION),
3883    new Permission(APIConstants.Permissions.API_CREATE, UserMgtConstants.EXECUTE_ACTION),
3884    new Permission(APIConstants.Permissions.CONFIGURE_GOVERNANCE, UserMgtConstants.EXECUTE_ACTION),
3885    new Permission(APIConstants.Permissions.RESOURCE_GOVERN, UserMgtConstants.EXECUTE_ACTION)};
3886  35 createRole(roleName, creatorPermissions, tenantId);
3887    }
3888   
3889    /**
3890    * Creates a role with a given set of permissions for the specified tenant
3891    *
3892    * @param roleName role name
3893    * @param permissions a set of permissions to be associated with the role
3894    * @param tenantId id of the tenant
3895    * @throws APIManagementException
3896    */
 
3897  118 toggle public static void createRole(String roleName, Permission[] permissions, int tenantId)
3898    throws APIManagementException {
3899  118 try {
3900  118 RealmService realmService = ServiceReferenceHolder.getInstance().getRealmService();
3901  118 UserRealm realm;
3902  118 org.wso2.carbon.user.api.UserRealm tenantRealm;
3903  118 UserStoreManager manager;
3904   
3905  118 if (tenantId < 0) {
3906  54 realm = realmService.getBootstrapRealm();
3907  54 manager = realm.getUserStoreManager();
3908    } else {
3909  64 tenantRealm = realmService.getTenantUserRealm(tenantId);
3910  64 manager = tenantRealm.getUserStoreManager();
3911    }
3912  118 if (!manager.isExistingRole(roleName)) {
3913  19 if (log.isDebugEnabled()) {
3914  2 log.debug("Creating role: " + roleName);
3915    }
3916  19 String tenantAdminName = ServiceReferenceHolder.getInstance().getRealmService()
3917    .getTenantUserRealm(tenantId).getRealmConfiguration().getAdminUserName();
3918  19 String[] userList = new String[]{tenantAdminName};
3919  19 manager.addRole(roleName, userList, permissions);
3920    }
3921    } catch (UserStoreException e) {
3922  0 throw new APIManagementException("Error while creating role: " + roleName, e);
3923    }
3924    }
3925   
 
3926  0 toggle public void setupSelfRegistration(APIManagerConfiguration config, int tenantId) throws APIManagementException {
3927  0 boolean enabled = Boolean.parseBoolean(config.getFirstProperty(APIConstants.SELF_SIGN_UP_ENABLED));
3928  0 if (!enabled) {
3929  0 return;
3930    }
3931    // Create the subscriber role as an internal role
3932  0 String role = UserCoreConstants.INTERNAL_DOMAIN + CarbonConstants.DOMAIN_SEPARATOR
3933    + config.getFirstProperty(APIConstants.SELF_SIGN_UP_ROLE);
3934  0 if ((UserCoreConstants.INTERNAL_DOMAIN + CarbonConstants.DOMAIN_SEPARATOR).equals(role)) {
3935    // Required parameter missing - Throw an exception and interrupt startup
3936  0 throw new APIManagementException("Required subscriber role parameter missing "
3937    + "in the self sign up configuration");
3938    }
3939   
3940  0 try {
3941  0 RealmService realmService = ServiceReferenceHolder.getInstance().getRealmService();
3942  0 UserRealm realm;
3943  0 org.wso2.carbon.user.api.UserRealm tenantRealm;
3944  0 UserStoreManager manager;
3945   
3946  0 if (tenantId < 0) {
3947  0 realm = realmService.getBootstrapRealm();
3948  0 manager = realm.getUserStoreManager();
3949    } else {
3950  0 tenantRealm = realmService.getTenantUserRealm(tenantId);
3951  0 manager = tenantRealm.getUserStoreManager();
3952    }
3953  0 if (!manager.isExistingRole(role)) {
3954  0 if (log.isDebugEnabled()) {
3955  0 log.debug("Creating subscriber role: " + role);
3956    }
3957  0 Permission[] subscriberPermissions = new Permission[]{
3958    new Permission("/permission/admin/login", UserMgtConstants.EXECUTE_ACTION),
3959    new Permission(APIConstants.Permissions.API_SUBSCRIBE, UserMgtConstants.EXECUTE_ACTION)};
3960  0 String tenantAdminName = ServiceReferenceHolder.getInstance().getRealmService()
3961    .getTenantUserRealm(tenantId).getRealmConfiguration().getAdminUserName();
3962  0 String[] userList = new String[]{tenantAdminName};
3963  0 manager.addRole(role, userList, subscriberPermissions);
3964    }
3965    } catch (UserStoreException e) {
3966  0 throw new APIManagementException("Error while creating subscriber role: " + role + " - "
3967    + "Self registration might not function properly.", e);
3968    }
3969    }
3970   
 
3971  0 toggle public static String removeAnySymbolFromUriTempate(String uriTemplate) {
3972  0 if (uriTemplate != null) {
3973  0 int anySymbolIndex = uriTemplate.indexOf("/*");
3974  0 if (anySymbolIndex != -1) {
3975  0 return uriTemplate.substring(0, anySymbolIndex);
3976    }
3977    }
3978  0 return uriTemplate;
3979    }
3980   
 
3981  0 toggle public static float getAverageRating(APIIdentifier apiId) throws APIManagementException {
3982  0 return ApiMgtDAO.getInstance().getAverageRating(apiId);
3983    }
3984   
 
3985  3497 toggle public static float getAverageRating(int apiId) throws APIManagementException {
3986  3497 return ApiMgtDAO.getInstance().getAverageRating(apiId);
3987    }
3988   
 
3989  0 toggle public static List<Tenant> getAllTenantsWithSuperTenant() throws UserStoreException {
3990  0 Tenant[] tenants = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager().getAllTenants();
3991  0 ArrayList<Tenant> tenantArrayList = new ArrayList<Tenant>();
3992  0 Collections.addAll(tenantArrayList, tenants);
3993  0 Tenant superAdminTenant = new Tenant();
3994  0 superAdminTenant.setDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
3995  0 superAdminTenant.setId(org.wso2.carbon.utils.multitenancy.MultitenantConstants.SUPER_TENANT_ID);
3996  0 superAdminTenant.setAdminName(CarbonConstants.REGISTRY_ANONNYMOUS_USERNAME);
3997  0 tenantArrayList.add(superAdminTenant);
3998  0 return tenantArrayList;
3999    }
4000   
4001    /**
4002    * In multi tenant environment, publishers should allow only to revoke the tokens generated within his domain.
4003    * Super tenant should not see the tenant created tokens and vise versa. This method is used to check the logged in
4004    * user have permissions to revoke a given users tokens.
4005    *
4006    * @param loggedInUser current logged in user to publisher
4007    * @param authorizedUser access token owner
4008    * @return
4009    */
 
4010  0 toggle public static boolean isLoggedInUserAuthorizedToRevokeToken(String loggedInUser, String authorizedUser) {
4011  0 String loggedUserTenantDomain = MultitenantUtils.getTenantDomain(loggedInUser);
4012  0 String authorizedUserTenantDomain = MultitenantUtils.getTenantDomain(authorizedUser);
4013   
4014  0 if (MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(loggedUserTenantDomain) && MultitenantConstants
4015    .SUPER_TENANT_DOMAIN_NAME.equals(authorizedUserTenantDomain)) {
4016  0 return true;
4017  0 } else if (authorizedUserTenantDomain.equals(loggedUserTenantDomain)) {
4018  0 return true;
4019    }
4020   
4021  0 return false;
4022    }
4023   
 
4024  110 toggle public static int getApplicationId(String appName, String userId) throws APIManagementException {
4025  110 return ApiMgtDAO.getInstance().getApplicationId(appName, userId);
4026    }
4027   
 
4028  594 toggle public static boolean isAPIManagementEnabled() {
4029  594 return Boolean.parseBoolean(CarbonUtils.getServerConfiguration().getFirstProperty("APIManagement.Enabled"));
4030    }
4031   
 
4032  18 toggle public static boolean isLoadAPIContextsAtStartup() {
4033  18 return Boolean.parseBoolean(CarbonUtils.getServerConfiguration().getFirstProperty(
4034    "APIManagement.LoadAPIContextsInServerStartup"));
4035    }
4036   
 
4037  0 toggle public static Set<APIStore> getExternalAPIStores(int tenantId) throws APIManagementException {
4038  0 SortedSet<APIStore> apistoreSet = new TreeSet<APIStore>(new APIStoreNameComparator());
4039  0 apistoreSet.addAll(getExternalStores(tenantId));
4040  0 return apistoreSet;
4041   
4042    }
4043   
 
4044  249 toggle public static boolean isAllowDisplayAPIsWithMultipleStatus() {
4045  249 APIManagerConfiguration config = ServiceReferenceHolder.getInstance().
4046    getAPIManagerConfigurationService().getAPIManagerConfiguration();
4047  249 String displayAllAPIs = config.getFirstProperty(APIConstants.API_STORE_DISPLAY_ALL_APIS);
4048  249 if (displayAllAPIs == null) {
4049  0 log.warn("The configurations related to show deprecated APIs in APIStore " +
4050    "are missing in api-manager.xml.");
4051  0 return false;
4052    }
4053  249 return Boolean.parseBoolean(displayAllAPIs);
4054    }
4055   
 
4056  222 toggle public static boolean isAllowDisplayMultipleVersions() {
4057  222 APIManagerConfiguration config = ServiceReferenceHolder.getInstance().
4058    getAPIManagerConfigurationService().getAPIManagerConfiguration();
4059   
4060  222 String displayMultiVersions = config.getFirstProperty(APIConstants.API_STORE_DISPLAY_MULTIPLE_VERSIONS);
4061  222 if (displayMultiVersions == null) {
4062  0 log.warn("The configurations related to show multiple versions of API in APIStore " +
4063    "are missing in api-manager.xml.");
4064  0 return false;
4065    }
4066  222 return Boolean.parseBoolean(displayMultiVersions);
4067    }
4068   
 
4069  0 toggle public static Set<APIStore> getExternalAPIStores(Set<APIStore> inputStores, int tenantId)
4070    throws APIManagementException {
4071  0 SortedSet<APIStore> apiStores = new TreeSet<APIStore>(new APIStoreNameComparator());
4072  0 apiStores.addAll(getExternalStores(tenantId));
4073    //Retains only the stores that contained in configuration
4074  0 inputStores.retainAll(apiStores);
4075  0 boolean exists = false;
4076  0 if (!apiStores.isEmpty()) {
4077  0 for (APIStore store : apiStores) {
4078  0 for (APIStore inputStore : inputStores) {
4079  0 if (inputStore.getName().equals(store.getName())) { // If the configured apistore already stored in
4080    // db,ignore adding it again
4081  0 exists = true;
4082    }
4083    }
4084  0 if (!exists) {
4085  0 inputStores.add(store);
4086    }
4087  0 exists = false;
4088    }
4089    }
4090  0 return inputStores;
4091    }
4092   
 
4093  359 toggle public static boolean isAPIsPublishToExternalAPIStores(int tenantId)
4094    throws APIManagementException {
4095  359 return !getExternalStores(tenantId).isEmpty();
4096    }
4097   
 
4098  177 toggle public static boolean isAPIGatewayKeyCacheEnabled() {
4099  177 try {
4100  177 APIManagerConfiguration config = ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService()
4101    .getAPIManagerConfiguration();
4102  177 String serviceURL = config.getFirstProperty(APIConstants.GATEWAY_TOKEN_CACHE_ENABLED);
4103  177 return Boolean.parseBoolean(serviceURL);
4104    } catch (Exception e) {
4105  0 log.error("Did not found valid API Validation Information cache configuration. Use default configuration"
4106    + e);
4107    }
4108  0 return true;
4109    }
4110   
4111   
 
4112  594 toggle public static Cache getAPIContextCache() {
4113  594 CacheManager contextCacheManager = Caching.getCacheManager(APIConstants.API_CONTEXT_CACHE_MANAGER).
4114    getCache(APIConstants.API_CONTEXT_CACHE).getCacheManager();
4115  594 if (!isContextCacheInitialized) {
4116  18 isContextCacheInitialized = true;
4117  18 return contextCacheManager.<String, Boolean>createCacheBuilder(APIConstants.API_CONTEXT_CACHE_MANAGER).
4118    setExpiry(CacheConfiguration.ExpiryType.MODIFIED, new CacheConfiguration.Duration(TimeUnit.DAYS,
4119    APIConstants.API_CONTEXT_CACHE_EXPIRY_TIME_IN_DAYS)).setStoreByValue(false).build();
4120    } else {
4121  576 return Caching.getCacheManager(APIConstants.API_CONTEXT_CACHE_MANAGER).getCache(APIConstants.API_CONTEXT_CACHE);
4122    }
4123    }
4124   
4125    /**
4126    * Get active tenant domains
4127    *
4128    * @return
4129    * @throws UserStoreException
4130    */
 
4131  59 toggle public static Set<String> getActiveTenantDomains() throws UserStoreException {
4132  59 Set<String> tenantDomains;
4133  59 Tenant[] tenants = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager().getAllTenants();
4134  59 if (tenants == null || tenants.length == 0) {
4135  0 tenantDomains = Collections.<String>emptySet();
4136    } else {
4137  59 tenantDomains = new HashSet<String>();
4138  59 for (Tenant tenant : tenants) {
4139  173 if (tenant.isActive()) {
4140  123 tenantDomains.add(tenant.getDomain());
4141    }
4142    }
4143  59 if (!tenantDomains.isEmpty()) {
4144  59 tenantDomains.add(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
4145    }
4146    }
4147  59 return tenantDomains;
4148    }
4149   
4150   
4151    /**
4152    * Retrieves the role list of system
4153    *
4154    * @throws APIManagementException If an error occurs
4155    */
 
4156  17 toggle public static String[] getRoleNames(String username) throws APIManagementException {
4157   
4158  17 String tenantDomain = MultitenantUtils.getTenantDomain(username);
4159  17 try {
4160  17 if (!org.wso2.carbon.utils.multitenancy.MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
4161  1 int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager()
4162    .getTenantId(tenantDomain);
4163  1 UserStoreManager manager = ServiceReferenceHolder.getInstance().getRealmService()
4164    .getTenantUserRealm(tenantId).getUserStoreManager();
4165   
4166  1 return manager.getRoleNames();
4167    } else {
4168  16 return AuthorizationManager.getInstance().getRoleNames();
4169    }
4170    } catch (UserStoreException e) {
4171  0 log.error("Error while getting all the roles", e);
4172  0 return new String[0];
4173   
4174    }
4175    }
4176   
4177    /**
4178    * check whether given role is exist
4179    *
4180    * @param userName logged user
4181    * @param roleName role name need to check
4182    * @return true if exist and false if not
4183    * @throws APIManagementException If an error occurs
4184    */
 
4185  5 toggle public static boolean isRoleNameExist(String userName, String roleName) throws APIManagementException {
4186  5 if (roleName == null || StringUtils.isEmpty(roleName.trim())) {
4187  0 return true;
4188    }
4189   
4190    //disable role validation if "disableRoleValidationAtScopeCreation" system property is set
4191  5 String disableRoleValidation = System.getProperty(DISABLE_ROLE_VALIDATION_AT_SCOPE_CREATION);
4192  5 if (Boolean.parseBoolean(disableRoleValidation)) {
4193  0 return true;
4194    }
4195   
4196  5 org.wso2.carbon.user.api.UserStoreManager userStoreManager;
4197  5 try {
4198  5 RealmService realmService = ServiceReferenceHolder.getInstance().getRealmService();
4199  5 int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager()
4200    .getTenantId(MultitenantUtils.getTenantDomain(userName));
4201  5 userStoreManager = realmService.getTenantUserRealm(tenantId).getUserStoreManager();
4202   
4203  5 String[] roles = roleName.split(",");
4204  5 for (String role : roles) {
4205  5 if (!userStoreManager.isExistingRole(role)) {
4206  1 return false;
4207    }
4208    }
4209    } catch (org.wso2.carbon.user.api.UserStoreException e) {
4210  0 log.error("Error when getting the list of roles", e);
4211    }
4212  4 return true;
4213    }
4214   
4215    /**
4216    * Create API Definition in JSON
4217    *
4218    * @param api API
4219    * @throws org.wso2.carbon.apimgt.api.APIManagementException if failed to generate the content and save
4220    * @deprecated
4221    */
4222   
 
4223  0 toggle @Deprecated
4224    public static String createSwaggerJSONContent(API api) throws APIManagementException {
4225  0 APIIdentifier identifier = api.getId();
4226   
4227  0 APIManagerConfiguration config = ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService()
4228    .getAPIManagerConfiguration();
4229   
4230  0 Environment environment = (Environment) config.getApiGatewayEnvironments().values().toArray()[0];
4231  0 String endpoints = environment.getApiGatewayEndpoint();
4232  0 String[] endpointsSet = endpoints.split(",");
4233  0 String apiContext = api.getContext();
4234  0 String version = identifier.getVersion();
4235  0 Set<URITemplate> uriTemplates = api.getUriTemplates();
4236  0 String description = api.getDescription();
4237   
4238    // With the new context version strategy, the URL prefix is the apiContext. the verison will be embedded in
4239    // the apiContext.
4240  0 String urlPrefix = apiContext;
4241   
4242  0 if (endpointsSet.length < 1) {
4243  0 throw new APIManagementException("Error in creating JSON representation of the API"
4244    + identifier.getApiName());
4245    }
4246  0 if (description == null || "".equals(description)) {
4247  0 description = "";
4248    } else {
4249  0 description = description.trim();
4250    }
4251   
4252  0 Map<String, List<Operation>> uriTemplateDefinitions = new HashMap<String, List<Operation>>();
4253  0 List<APIResource> apis = new ArrayList<APIResource>();
4254  0 for (URITemplate template : uriTemplates) {
4255  0 List<Operation> ops;
4256  0 List<Parameter> parameters;
4257  0 String path = urlPrefix + APIUtil.removeAnySymbolFromUriTempate(template.getUriTemplate());
4258    /* path exists in uriTemplateDefinitions */
4259  0 if (uriTemplateDefinitions.get(path) != null) {
4260  0 ops = uriTemplateDefinitions.get(path);
4261  0 parameters = new ArrayList<Parameter>();
4262   
4263  0 String httpVerb = template.getHTTPVerb();
4264    /* For GET and DELETE Parameter name - Query Parameters */
4265  0 if (Constants.Configuration.HTTP_METHOD_GET.equals(httpVerb)
4266    || Constants.Configuration.HTTP_METHOD_DELETE.equals(httpVerb)) {
4267  0 Parameter queryParam = new Parameter(APIConstants.OperationParameter.QUERY_PARAM_NAME,
4268    APIConstants.OperationParameter.QUERY_PARAM_DESCRIPTION,
4269    APIConstants.OperationParameter.PAYLOAD_PARAM_TYPE, false, false, "String");
4270  0 parameters.add(queryParam);
4271    } else {/* For POST, PUT and PATCH Parameter name - Payload */
4272  0 Parameter payLoadParam = new Parameter(APIConstants.OperationParameter.PAYLOAD_PARAM_NAME,
4273    APIConstants.OperationParameter.PAYLOAD_PARAM_DESCRIPTION,
4274    APIConstants.OperationParameter.PAYLOAD_PARAM_TYPE, false, false, "String");
4275  0 parameters.add(payLoadParam);
4276    }
4277   
4278  0 Parameter authParam = new Parameter(APIConstants.OperationParameter.AUTH_PARAM_NAME,
4279    APIConstants.OperationParameter.AUTH_PARAM_DESCRIPTION,
4280    APIConstants.OperationParameter.AUTH_PARAM_TYPE, false, false, "String");
4281  0 parameters.add(authParam);
4282  0 if (!"OPTIONS".equals(httpVerb)) {
4283  0 Operation op = new Operation(httpVerb, description, description, parameters);
4284  0 ops.add(op);
4285    }
4286    } else {/* path not exists in uriTemplateDefinitions */
4287  0 ops = new ArrayList<Operation>();
4288  0 parameters = new ArrayList<Parameter>();
4289   
4290  0 String httpVerb = template.getHTTPVerb();
4291    /* For GET and DELETE Parameter name - Query Parameters */
4292  0 if (Constants.Configuration.HTTP_METHOD_GET.equals(httpVerb)
4293    || Constants.Configuration.HTTP_METHOD_DELETE.equals(httpVerb)) {
4294  0 Parameter queryParam = new Parameter(APIConstants.OperationParameter.QUERY_PARAM_NAME,
4295    APIConstants.OperationParameter.QUERY_PARAM_DESCRIPTION,
4296    APIConstants.OperationParameter.PAYLOAD_PARAM_TYPE, false, false, "String");
4297  0 parameters.add(queryParam);
4298    } else {/* For POST,PUT and PATCH Parameter name - Payload */
4299  0 Parameter payLoadParam = new Parameter(APIConstants.OperationParameter.PAYLOAD_PARAM_NAME,
4300    APIConstants.OperationParameter.PAYLOAD_PARAM_DESCRIPTION,
4301    APIConstants.OperationParameter.PAYLOAD_PARAM_TYPE, false, false, "String");
4302  0 parameters.add(payLoadParam);
4303    }
4304  0 Parameter authParam = new Parameter(APIConstants.OperationParameter.AUTH_PARAM_NAME,
4305    APIConstants.OperationParameter.AUTH_PARAM_DESCRIPTION,
4306    APIConstants.OperationParameter.AUTH_PARAM_TYPE, false, false, "String");
4307  0 parameters.add(authParam);
4308  0 if (!"OPTIONS".equals(httpVerb)) {
4309  0 Operation op = new Operation(httpVerb, description, description, parameters);
4310  0 ops.add(op);
4311    }
4312  0 uriTemplateDefinitions.put(path, ops);
4313    }
4314    }
4315   
4316  0 final Set<Entry<String, List<Operation>>> entries = uriTemplateDefinitions.entrySet();
4317   
4318  0 for (Entry entry : entries) {
4319  0 APIResource apiResource = new APIResource((String) entry.getKey(), description,
4320    (List<Operation>) entry.getValue());
4321  0 apis.add(apiResource);
4322    }
4323  0 APIDefinition apidefinition = new APIDefinition(version, APIConstants.SWAGGER_VERSION, endpointsSet[0],
4324    apiContext, apis);
4325   
4326  0 Gson gson = new Gson();
4327  0 return gson.toJson(apidefinition);
4328    }
4329   
4330    /**
4331    * Helper method to get tenantId from userName
4332    *
4333    * @param userName user name
4334    * @return tenantId
4335    */
 
4336  3146 toggle public static int getTenantId(String userName) {
4337    //get tenant domain from user name
4338  3146 String tenantDomain = MultitenantUtils.getTenantDomain(userName);
4339  3146 return getTenantIdFromTenantDomain(tenantDomain);
4340    }
4341   
4342    /**
4343    * Helper method to get tenantId from tenantDomain
4344    *
4345    * @param tenantDomain tenant Domain
4346    * @return tenantId
4347    */
 
4348  3464 toggle public static int getTenantIdFromTenantDomain(String tenantDomain) {
4349  3464 RealmService realmService = ServiceReferenceHolder.getInstance().getRealmService();
4350   
4351  3464 if (realmService == null || tenantDomain == null) {
4352  8 return MultitenantConstants.SUPER_TENANT_ID;
4353    }
4354   
4355  3456 try {
4356  3456 return realmService.getTenantManager().getTenantId(tenantDomain);
4357    } catch (UserStoreException e) {
4358  0 log.error(e.getMessage(), e);
4359    }
4360   
4361  0 return -1;
4362    }
4363   
4364    /**
4365    * Helper method to get tenantDomain from tenantId
4366    *
4367    * @param tenantId tenant Id
4368    * @return tenantId
4369    */
 
4370  3331 toggle public static String getTenantDomainFromTenantId(int tenantId) {
4371  3331 RealmService realmService = ServiceReferenceHolder.getInstance().getRealmService();
4372   
4373  3331 if (realmService == null) {
4374  0 return MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
4375    }
4376   
4377  3331 try {
4378  3331 return realmService.getTenantManager().getDomain(tenantId);
4379    } catch (UserStoreException e) {
4380  0 log.error(e.getMessage(), e);
4381    }
4382  0 return null;
4383    }
4384   
 
4385  0 toggle public static int getSuperTenantId() {
4386  0 return MultitenantConstants.SUPER_TENANT_ID;
4387    }
4388   
4389    /**
4390    * Helper method to get username with tenant domain.
4391    *
4392    * @param userName
4393    * @return userName with tenant domain
4394    */
 
4395  12 toggle public static String getUserNameWithTenantSuffix(String userName) {
4396  12 String userNameWithTenantPrefix = userName;
4397  12 String tenantDomain = MultitenantUtils.getTenantDomain(userName);
4398  12 if (userName != null && !userName.endsWith("@" + MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)
4399    && MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
4400  0 userNameWithTenantPrefix = userName + "@" + tenantDomain;
4401    }
4402   
4403  12 return userNameWithTenantPrefix;
4404    }
4405   
4406    /**
4407    * Build OMElement from inputstream
4408    *
4409    * @param inputStream
4410    * @return
4411    * @throws Exception
4412    */
 
4413  562 toggle public static OMElement buildOMElement(InputStream inputStream) throws Exception {
4414  562 XMLStreamReader parser;
4415  562 StAXOMBuilder builder;
4416  562 try {
4417  562 XMLInputFactory factory = XMLInputFactory.newInstance();
4418  562 factory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
4419  562 parser = factory.createXMLStreamReader(inputStream);
4420  562 builder = new StAXOMBuilder(parser);
4421    } catch (XMLStreamException e) {
4422  0 String msg = "Error in initializing the parser.";
4423  0 log.error(msg, e);
4424  0 throw new Exception(msg, e);
4425    }
4426   
4427  562 return builder.getDocumentElement();
4428    }
4429   
4430   
4431    /**
4432    * Get stored in sequences, out sequences and fault sequences from the governanceSystem registry
4433    *
4434    * @param sequenceName -The sequence to be retrieved
4435    * @param tenantId
4436    * @param direction - Direction indicates which sequences to fetch. Values would be
4437    * "in", "out" or "fault"
4438    * @return
4439    * @throws APIManagementException
4440    */
 
4441  2 toggle public static OMElement getCustomSequence(String sequenceName, int tenantId, String direction,
4442    APIIdentifier identifier) throws APIManagementException {
4443  2 org.wso2.carbon.registry.api.Collection seqCollection = null;
4444   
4445  2 try {
4446  2 UserRegistry registry = ServiceReferenceHolder.getInstance().getRegistryService()
4447    .getGovernanceSystemRegistry(tenantId);
4448   
4449  2 if ("in".equals(direction)) {
4450  1 seqCollection = (org.wso2.carbon.registry.api.Collection) registry
4451    .get(APIConstants.API_CUSTOM_INSEQUENCE_LOCATION);
4452  1 } else if ("out".equals(direction)) {
4453  1 seqCollection = (org.wso2.carbon.registry.api.Collection) registry
4454    .get(APIConstants.API_CUSTOM_OUTSEQUENCE_LOCATION);
4455  0 } else if ("fault".equals(direction)) {
4456  0 seqCollection = (org.wso2.carbon.registry.api.Collection) registry
4457    .get(APIConstants.API_CUSTOM_FAULTSEQUENCE_LOCATION);
4458    }
4459   
4460  2 if (seqCollection == null) {
4461  0 seqCollection = (org.wso2.carbon.registry.api.Collection) registry.get(getSequencePath(identifier,
4462    direction));
4463   
4464    }
4465   
4466  2 if (seqCollection != null) {
4467  2 String[] childPaths = seqCollection.getChildren();
4468   
4469  2 for (String childPath : childPaths) {
4470  13 Resource sequence = registry.get(childPath);
4471  13 OMElement seqElment = APIUtil.buildOMElement(sequence.getContentStream());
4472  13 if (sequenceName.equals(seqElment.getAttributeValue(new QName("name")))) {
4473  1 return seqElment;
4474    }
4475    }
4476    }
4477   
4478    // If the sequence not found the default sequences, check in custom sequences
4479   
4480  1 seqCollection = (org.wso2.carbon.registry.api.Collection) registry.get(getSequencePath(identifier,
4481    direction));
4482  1 if (seqCollection != null) {
4483  1 String[] childPaths = seqCollection.getChildren();
4484   
4485  1 for (String childPath : childPaths) {
4486  1 Resource sequence = registry.get(childPath);
4487  1 OMElement seqElment = APIUtil.buildOMElement(sequence.getContentStream());
4488  1 if (sequenceName.equals(seqElment.getAttributeValue(new QName("name")))) {
4489  1 return seqElment;
4490    }
4491    }
4492    }
4493   
4494    } catch (Exception e) {
4495  0 String msg = "Issue is in accessing the Registry";
4496  0 log.error(msg);
4497  0 throw new APIManagementException(msg, e);
4498    }
4499  0 return null;
4500    }
4501   
4502    /**
4503    * Returns true if the sequence is a per API one
4504    *
4505    * @param sequenceName
4506    * @param tenantId
4507    * @param identifier API identifier
4508    * @param sequenceType in/out/fault
4509    * @return true/false
4510    * @throws APIManagementException
4511    */
 
4512  0 toggle public static boolean isPerAPISequence(String sequenceName, int tenantId, APIIdentifier identifier,
4513    String sequenceType) throws APIManagementException {
4514  0 org.wso2.carbon.registry.api.Collection seqCollection = null;
4515  0 try {
4516  0 UserRegistry registry = ServiceReferenceHolder.getInstance().getRegistryService()
4517    .getGovernanceSystemRegistry(tenantId);
4518   
4519    // If the sequence not found the default sequences, check in custom sequences
4520   
4521  0 if (registry.resourceExists(getSequencePath(identifier, sequenceType))) {
4522   
4523  0 seqCollection = (org.wso2.carbon.registry.api.Collection) registry.get(getSequencePath(identifier,
4524    sequenceType));
4525  0 if (seqCollection != null) {
4526  0 String[] childPaths = seqCollection.getChildren();
4527   
4528  0 for (String childPath : childPaths) {
4529  0 Resource sequence = registry.get(childPath);
4530  0 OMElement seqElment = APIUtil.buildOMElement(sequence.getContentStream());
4531  0 if (sequenceName.equals(seqElment.getAttributeValue(new QName("name")))) {
4532  0 return true;
4533    }
4534    }
4535    }
4536    }
4537   
4538   
4539    } catch (RegistryException e) {
4540  0 String msg = "Error while retrieving registry for tenant " + tenantId;
4541  0 log.error(msg);
4542  0 throw new APIManagementException(msg, e);
4543    } catch (org.wso2.carbon.registry.api.RegistryException e) {
4544  0 String msg = "Error while processing the " + sequenceType + " sequences of " + identifier
4545    + " in the registry";
4546  0 log.error(msg);
4547  0 throw new APIManagementException(msg, e);
4548    } catch (Exception e) {
4549  0 throw new APIManagementException(e.getMessage(), e);
4550    }
4551  0 return false;
4552    }
4553   
4554    /**
4555    * Returns uuid correspond to the given sequence name and direction
4556    *
4557    * @param sequenceName name of the sequence
4558    * @param tenantId logged in user's tenantId
4559    * @param direction in/out/fault
4560    * @param identifier API identifier
4561    * @return uuid of the given mediation sequence or null
4562    * @throws APIManagementException If failed to get the uuid of the mediation sequence
4563    */
 
4564  0 toggle public static String getMediationSequenceUuid(String sequenceName, int tenantId, String direction,
4565    APIIdentifier identifier) throws
4566    APIManagementException {
4567  0 org.wso2.carbon.registry.api.Collection seqCollection = null;
4568  0 String seqCollectionPath;
4569   
4570  0 try {
4571  0 UserRegistry registry = ServiceReferenceHolder.getInstance().getRegistryService()
4572    .getGovernanceSystemRegistry(tenantId);
4573   
4574  0 if ("in".equals(direction)) {
4575  0 seqCollection = (org.wso2.carbon.registry.api.Collection) registry
4576    .get(APIConstants.API_CUSTOM_SEQUENCE_LOCATION + File.separator +
4577    APIConstants.API_CUSTOM_SEQUENCE_TYPE_IN);
4578  0 } else if ("out".equals(direction)) {
4579  0 seqCollection = (org.wso2.carbon.registry.api.Collection) registry
4580    .get(APIConstants.API_CUSTOM_SEQUENCE_LOCATION + File.separator +
4581    APIConstants.API_CUSTOM_SEQUENCE_TYPE_OUT);
4582  0 } else if ("fault".equals(direction)) {
4583  0 seqCollection = (org.wso2.carbon.registry.api.Collection) registry
4584    .get(APIConstants.API_CUSTOM_SEQUENCE_LOCATION + File.separator +
4585    APIConstants.API_CUSTOM_SEQUENCE_TYPE_FAULT);
4586    }
4587   
4588  0 if (seqCollection == null) {
4589  0 seqCollection = (org.wso2.carbon.registry.api.Collection) registry.get
4590    (getSequencePath(identifier,
4591    direction));
4592   
4593    }
4594  0 if (seqCollection != null) {
4595  0 String[] childPaths = seqCollection.getChildren();
4596  0 for (String childPath : childPaths) {
4597  0 Resource sequence = registry.get(childPath);
4598  0 OMElement seqElment = APIUtil.buildOMElement(sequence.getContentStream());
4599  0 String seqElmentName = seqElment.getAttributeValue(new QName("name"));
4600  0 if (sequenceName.equals(seqElmentName)) {
4601  0 return sequence.getUUID();
4602    }
4603    }
4604    }
4605   
4606    // If the sequence not found the default sequences, check in custom sequences
4607   
4608  0 seqCollection = (org.wso2.carbon.registry.api.Collection) registry.get
4609    (getSequencePath(identifier, direction));
4610  0 if (seqCollection != null) {
4611  0 String[] childPaths = seqCollection.getChildren();
4612  0 for (String childPath : childPaths) {
4613  0 Resource sequence = registry.get(childPath);
4614  0 OMElement seqElment = APIUtil.buildOMElement(sequence.getContentStream());
4615  0 if (sequenceName.equals(seqElment.getAttributeValue(new QName("name")))) {
4616  0 return sequence.getUUID();
4617    }
4618    }
4619    }
4620   
4621    } catch (Exception e) {
4622  0 String msg = "Issue is in accessing the Registry";
4623  0 log.error(msg);
4624  0 throw new APIManagementException(msg, e);
4625    }
4626  0 return null;
4627    }
4628   
4629    /**
4630    * Returns true if sequence is set
4631    *
4632    * @param sequence
4633    * @return
4634    */
 
4635  1472 toggle public static boolean isSequenceDefined(String sequence) {
4636  1472 return sequence != null && !"none".equals(sequence);
4637    }
4638   
4639    /**
4640    * Return the sequence extension name.
4641    * eg: admin--testAPi--v1.00
4642    *
4643    * @param api
4644    * @return
4645    */
 
4646  256 toggle public static String getSequenceExtensionName(API api) {
4647  256 return api.getId().getProviderName() + "--" + api.getId().getApiName() + ":v" + api.getId().getVersion();
4648    }
4649   
4650    /**
4651    * @param token
4652    * @return
4653    */
 
4654  1371 toggle public static String decryptToken(String token) throws CryptoException {
4655  1371 APIManagerConfiguration config = ServiceReferenceHolder.getInstance().
4656    getAPIManagerConfigurationService().getAPIManagerConfiguration();
4657   
4658  1371 if (Boolean.parseBoolean(config.getFirstProperty(APIConstants.ENCRYPT_TOKENS_ON_PERSISTENCE))) {
4659  0 return new String(CryptoUtil.getDefaultCryptoUtil().base64DecodeAndDecrypt(token), Charset.defaultCharset());
4660    }
4661   
4662  1371 String enableTokenHashMode = config.getFirstProperty(APIConstants.HASH_TOKENS_ON_PERSISTENCE);
4663  1371 if (enableTokenHashMode != null && Boolean.parseBoolean(enableTokenHashMode)) {
4664  0 return null;
4665    }
4666  1371 return token;
4667    }
4668   
4669    /**
4670    * @param token
4671    * @return
4672    */
 
4673  2 toggle public static String encryptToken(String token) throws CryptoException, APIManagementException {
4674  2 APIManagerConfiguration config = ServiceReferenceHolder.getInstance().
4675    getAPIManagerConfigurationService().getAPIManagerConfiguration();
4676   
4677  2 if (Boolean.parseBoolean(config.getFirstProperty(APIConstants.ENCRYPT_TOKENS_ON_PERSISTENCE))) {
4678  0 return CryptoUtil.getDefaultCryptoUtil().encryptAndBase64Encode(token.getBytes(Charset.defaultCharset()));
4679    }
4680   
4681  2 String enableTokenHashMode = config.getFirstProperty(APIConstants.HASH_TOKENS_ON_PERSISTENCE);
4682  2 if (enableTokenHashMode != null && Boolean.parseBoolean(enableTokenHashMode)) {
4683  0 return hash(token);
4684    }
4685  2 return token;
4686    }
4687   
4688    /**
4689    * Method to generate hash value.
4690    *
4691    * @param plainText Plain text value.
4692    * @return hashed value.
4693    */
 
4694  0 toggle private static String hash(String plainText) throws APIManagementException {
4695   
4696  0 if (log.isDebugEnabled()) {
4697  0 log.debug("Hashing the token for " + plainText);
4698    }
4699   
4700  0 if (StringUtils.isEmpty(plainText)) {
4701  0 throw new APIManagementException("plainText value is null or empty to be hash.");
4702    }
4703   
4704  0 MessageDigest messageDigest = null;
4705  0 byte[] hash = null;
4706  0 String hashAlgorithm = OAuthServerConfiguration.getInstance().getHashAlgorithm();
4707  0 if (log.isDebugEnabled()) {
4708  0 log.debug("Getting the hash algorithm from the configuration: " + hashAlgorithm);
4709    }
4710  0 try {
4711  0 messageDigest = MessageDigest.getInstance(hashAlgorithm);
4712  0 messageDigest.update(plainText.getBytes());
4713  0 hash = messageDigest.digest();
4714    } catch (NoSuchAlgorithmException e) {
4715  0 throw new APIManagementException(
4716    "Error while retrieving MessageDigest for the provided hash algorithm: " + hashAlgorithm, e);
4717    }
4718  0 JSONObject object = new JSONObject();
4719  0 object.put("algorithm", hashAlgorithm);
4720  0 object.put("hash", bytesToHex(hash));
4721   
4722  0 return object.toString();
4723    }
4724   
 
4725  0 toggle private static String bytesToHex(byte[] bytes) {
4726   
4727  0 StringBuilder result = new StringBuilder();
4728  0 for (byte byt : bytes) {
4729  0 result.append(Integer.toString((byt & 0xff) + 0x100, 16).substring(1));
4730    }
4731  0 return result.toString();
4732    }
4733   
 
4734  1140 toggle public static void loadTenantRegistry(int tenantId) throws RegistryException {
4735  1140 TenantRegistryLoader tenantRegistryLoader = APIManagerComponent.getTenantRegistryLoader();
4736  1140 ServiceReferenceHolder.getInstance().getIndexLoaderService().loadTenantIndex(tenantId);
4737  1140 tenantRegistryLoader.loadTenantRegistry(tenantId);
4738    }
4739   
4740    /**
4741    * This is to get the registry resource's HTTP permlink path.
4742    * Once this issue is fixed (https://wso2.org/jira/browse/REGISTRY-2110),
4743    * we can remove this method, and get permlink from the resource.
4744    *
4745    * @param path - Registry resource path
4746    * @return {@link String} -HTTP permlink
4747    */
 
4748  2 toggle public static String getRegistryResourceHTTPPermlink(String path) {
4749  2 String schemeHttp = APIConstants.HTTP_PROTOCOL;
4750  2 String schemeHttps = APIConstants.HTTPS_PROTOCOL;
4751   
4752  2 ConfigurationContextService contetxservice = ServiceReferenceHolder.getContextService();
4753    //First we will try to generate http permalink and if its disabled then only we will consider https
4754  2 int port = CarbonUtils.getTransportProxyPort(contetxservice.getServerConfigContext(), schemeHttp);
4755  2 if (port == -1) {
4756  2 port = CarbonUtils.getTransportPort(contetxservice.getServerConfigContext(), schemeHttp);
4757    }
4758    //getting https parameters if http is disabled. If proxy port is not present we will go for default port
4759  2 if (port == -1) {
4760  0 port = CarbonUtils.getTransportProxyPort(contetxservice.getServerConfigContext(), schemeHttps);
4761    }
4762  2 if (port == -1) {
4763  0 port = CarbonUtils.getTransportPort(contetxservice.getServerConfigContext(), schemeHttps);
4764    }
4765   
4766  2 String webContext = ServerConfiguration.getInstance().getFirstProperty("WebContextRoot");
4767   
4768  2 if (webContext == null || "/".equals(webContext)) {
4769  2 webContext = "";
4770    }
4771  2 RegistryService registryService = ServiceReferenceHolder.getInstance().getRegistryService();
4772  2 String version = "";
4773  2 if (registryService == null) {
4774  0 log.error("Registry Service has not been set.");
4775  2 } else if (path != null) {
4776  2 try {
4777  2 String[] versions = registryService.getRegistry(
4778    CarbonConstants.REGISTRY_SYSTEM_USERNAME,
4779    CarbonContext.getThreadLocalCarbonContext().getTenantId()).getVersions(path);
4780  2 if (versions != null && versions.length > 0) {
4781  0 version = versions[0].substring(versions[0].lastIndexOf(";version:"));
4782    }
4783    } catch (RegistryException e) {
4784  0 log.error("An error occurred while determining the latest version of the " +
4785    "resource at the given path: " + path, e);
4786    }
4787    }
4788  2 if (port != -1 && path != null) {
4789  2 String tenantDomain =
4790    PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(true);
4791  2 return webContext +
4792  2 ((tenantDomain != null &&
4793    !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) ?
4794    "/" + MultitenantConstants.TENANT_AWARE_URL_PREFIX + "/" + tenantDomain :
4795    "") +
4796    "/registry/resource" +
4797    org.wso2.carbon.registry.app.Utils.encodeRegistryPath(path) + version;
4798    }
4799  0 return null;
4800    }
4801   
4802   
 
4803  457 toggle public static boolean isSandboxEndpointsExists(API api) {
4804  457 JSONParser parser = new JSONParser();
4805  457 JSONObject config = null;
4806  457 try {
4807  457 config = (JSONObject) parser.parse(api.getEndpointConfig());
4808   
4809  457 if (config.containsKey("sandbox_endpoints")) {
4810  44 return true;
4811    }
4812    } catch (ParseException e) {
4813  0 log.error(APIConstants.MSG_JSON_PARSE_ERROR, e);
4814    } catch (ClassCastException e) {
4815  0 log.error(APIConstants.MSG_JSON_PARSE_ERROR, e);
4816    }
4817  413 return false;
4818    }
4819   
 
4820  457 toggle public static boolean isProductionEndpointsExists(API api) {
4821  457 JSONParser parser = new JSONParser();
4822  457 JSONObject config = null;
4823  457 try {
4824  457 config = (JSONObject) parser.parse(api.getEndpointConfig());
4825   
4826  457 if (config.containsKey("production_endpoints")) {
4827  457 return true;
4828    }
4829    } catch (ParseException e) {
4830  0 log.error(APIConstants.MSG_JSON_PARSE_ERROR, e);
4831    } catch (ClassCastException e) {
4832  0 log.error(APIConstants.MSG_JSON_PARSE_ERROR, e);
4833    }
4834  0 return false;
4835    }
4836   
4837    /**
4838    * This method used to get API minimum information from governance artifact
4839    *
4840    * @param artifact API artifact
4841    * @param registry Registry
4842    * @return API
4843    * @throws APIManagementException if failed to get API from artifact
4844    */
 
4845  113 toggle public static API getAPIInformation(GovernanceArtifact artifact, Registry registry) throws APIManagementException {
4846  113 API api;
4847  113 try {
4848  113 String providerName = artifact.getAttribute(APIConstants.API_OVERVIEW_PROVIDER);
4849  113 String apiName = artifact.getAttribute(APIConstants.API_OVERVIEW_NAME);
4850  113 String apiVersion = artifact.getAttribute(APIConstants.API_OVERVIEW_VERSION);
4851  113 api = new API(new APIIdentifier(providerName, apiName, apiVersion));
4852    //set uuid
4853  113 api.setUUID(artifact.getId());
4854  113 api.setThumbnailUrl(artifact.getAttribute(APIConstants.API_OVERVIEW_THUMBNAIL_URL));
4855  113 api.setStatus(getLcStateFromArtifact(artifact));
4856  113 api.setContext(artifact.getAttribute(APIConstants.API_OVERVIEW_CONTEXT));
4857  113 api.setVisibility(artifact.getAttribute(APIConstants.API_OVERVIEW_VISIBILITY));
4858  113 api.setVisibleRoles(artifact.getAttribute(APIConstants.API_OVERVIEW_VISIBLE_ROLES));
4859  113 api.setVisibleTenants(artifact.getAttribute(APIConstants.API_OVERVIEW_VISIBLE_TENANTS));
4860  113 api.setTransports(artifact.getAttribute(APIConstants.API_OVERVIEW_TRANSPORTS));
4861  113 api.setInSequence(artifact.getAttribute(APIConstants.API_OVERVIEW_INSEQUENCE));
4862  113 api.setOutSequence(artifact.getAttribute(APIConstants.API_OVERVIEW_OUTSEQUENCE));
4863  113 api.setFaultSequence(artifact.getAttribute(APIConstants.API_OVERVIEW_FAULTSEQUENCE));
4864  113 api.setDescription(artifact.getAttribute(APIConstants.API_OVERVIEW_DESCRIPTION));
4865  113 api.setRedirectURL(artifact.getAttribute(APIConstants.API_OVERVIEW_REDIRECT_URL));
4866  113 api.setBusinessOwner(artifact.getAttribute(APIConstants.API_OVERVIEW_BUSS_OWNER));
4867  113 api.setApiOwner(artifact.getAttribute(APIConstants.API_OVERVIEW_OWNER));
4868  113 api.setAdvertiseOnly(Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_ADVERTISE_ONLY)));
4869  113 String environments = artifact.getAttribute(APIConstants.API_OVERVIEW_ENVIRONMENTS);
4870  113 api.setEnvironments(extractEnvironmentsForAPI(environments));
4871  113 api.setCorsConfiguration(getCorsConfigurationFromArtifact(artifact));
4872  113 String artifactPath = GovernanceUtils.getArtifactPath(registry, artifact.getId());
4873  113 api.setLastUpdated(registry.get(artifactPath).getLastModified());
4874  113 api.setCreatedTime(String.valueOf(registry.get(artifactPath).getCreatedTime().getTime()));
4875   
4876    } catch (GovernanceException e) {
4877  0 String msg = "Failed to get API from artifact ";
4878  0 throw new APIManagementException(msg, e);
4879    } catch (RegistryException e) {
4880  0 String msg = "Failed to get LastAccess time or Rating";
4881  0 throw new APIManagementException(msg, e);
4882    }
4883  113 return api;
4884    }
4885   
4886    /**
4887    * Get the cache key of the ResourceInfoDTO
4888    *
4889    * @param apiContext - Context of the API
4890    * @param apiVersion - API Version
4891    * @param resourceUri - The resource uri Ex: /name/version
4892    * @param httpMethod - The http method. Ex: GET, POST
4893    * @return - The cache key
4894    */
 
4895  288 toggle public static String getResourceInfoDTOCacheKey(String apiContext, String apiVersion,
4896    String resourceUri, String httpMethod) {
4897  288 return apiContext + "/" + apiVersion + resourceUri + ":" + httpMethod;
4898    }
4899   
4900   
4901    /**
4902    * Get the key of the Resource ( used in scopes)
4903    *
4904    * @param api - API
4905    * @param template - URI Template
4906    * @return - The resource key
4907    */
 
4908  26 toggle public static String getResourceKey(API api, URITemplate template) {
4909  26 return APIUtil.getResourceKey(api.getContext(), api.getId().getVersion(), template.getUriTemplate(),
4910    template.getHTTPVerb());
4911    }
4912   
4913    /**
4914    * Get the key of the Resource ( used in scopes)
4915    *
4916    * @param apiContext - Context of the API
4917    * @param apiVersion - API Version
4918    * @param resourceUri - The resource uri Ex: /name/version
4919    * @param httpMethod - The http method. Ex: GET, POST
4920    * @return - The resource key
4921    */
 
4922  6360 toggle public static String getResourceKey(String apiContext, String apiVersion, String resourceUri, String httpMethod) {
4923  6360 return apiContext + "/" + apiVersion + resourceUri + ":" + httpMethod;
4924    }
4925   
4926    /**
4927    * Find scope object in a set based on the key
4928    *
4929    * @param scopes - Set of scopes
4930    * @param key - Key to search with
4931    * @return Scope - scope object
4932    */
 
4933  6692 toggle public static Scope findScopeByKey(Set<Scope> scopes, String key) {
4934  6692 for (Scope scope : scopes) {
4935  948 if (scope.getKey().equals(key)) {
4936  362 return scope;
4937    }
4938    }
4939  6330 return null;
4940    }
4941   
4942    /**
4943    * Get the cache key of the APIInfoDTO
4944    *
4945    * @param apiContext - Context of the API
4946    * @param apiVersion - API Version
4947    * @return - The cache key of the APIInfoDTO
4948    */
 
4949  155 toggle public static String getAPIInfoDTOCacheKey(String apiContext, String apiVersion) {
4950  155 return apiContext + "/" + apiVersion;
4951    }
4952   
4953    /**
4954    * Get the cache key of the Access Token
4955    *
4956    * @param accessToken - The access token which is cached
4957    * @param apiContext - The context of the API
4958    * @param apiVersion - The version of the API
4959    * @param resourceUri - The value of the resource url
4960    * @param httpVerb - The http method. Ex: GET, POST
4961    * @param authLevel - Required Authentication level. Ex: Application/Application User
4962    * @return - The Key which will be used to cache the access token
4963    */
 
4964  325 toggle public static String getAccessTokenCacheKey(String accessToken, String apiContext, String apiVersion,
4965    String resourceUri, String httpVerb, String authLevel) {
4966  325 return accessToken + ':' + apiContext + '/' + apiVersion + resourceUri + ':' + httpVerb + ':' + authLevel;
4967    }
4968   
4969   
4970    /**
4971    * Resolves system properties and replaces in given in text
4972    *
4973    * @param text
4974    * @return System properties resolved text
4975    */
 
4976  8751 toggle public static String replaceSystemProperty(String text) {
4977  8751 int indexOfStartingChars = -1;
4978  8751 int indexOfClosingBrace;
4979   
4980    // The following condition deals with properties.
4981    // Properties are specified as ${system.property},
4982    // and are assumed to be System properties
4983  ? while (indexOfStartingChars < text.indexOf("${")
4984    && (indexOfStartingChars = text.indexOf("${")) != -1
4985    && (indexOfClosingBrace = text.indexOf('}')) != -1) { // Is a
4986    // property
4987    // used?
4988  2354 String sysProp = text.substring(indexOfStartingChars + 2,
4989    indexOfClosingBrace);
4990  2354 String propValue = System.getProperty(sysProp);
4991   
4992  2354 if (propValue == null) {
4993  1218 if ("carbon.context".equals(sysProp)) {
4994  252 propValue = ServiceReferenceHolder.getContextService().getServerConfigContext().getContextRoot();
4995  966 } else if ("admin.username".equals(sysProp) || "admin.password".equals(sysProp)) {
4996  966 try {
4997  966 RealmConfiguration realmConfig =
4998    new RealmConfigXMLProcessor().buildRealmConfigurationFromFile();
4999  966 if ("admin.username".equals(sysProp)) {
5000  483 propValue = realmConfig.getAdminUserName();
5001    } else {
5002  483 propValue = realmConfig.getAdminPassword();
5003    }
5004    } catch (UserStoreException e) {
5005    // Can't throw an exception because the server is
5006    // starting and can't be halted.
5007  0 log.error("Unable to build the Realm Configuration", e);
5008  0 return null;
5009    }
5010    }
5011    }
5012    //Derive original text value with resolved system property value
5013  2354 if (propValue != null) {
5014  2354 text = text.substring(0, indexOfStartingChars) + propValue
5015    + text.substring(indexOfClosingBrace + 1);
5016    }
5017  2354 if ("carbon.home".equals(sysProp) && propValue != null
5018    && ".".equals(propValue)) {
5019  0 text = new File(".").getAbsolutePath() + File.separator + text;
5020    }
5021    }
5022  8751 return text;
5023    }
5024   
 
5025  0 toggle public static String encryptPassword(String plainTextPassword) throws APIManagementException {
5026  0 try {
5027  0 return CryptoUtil.getDefaultCryptoUtil().encryptAndBase64Encode(plainTextPassword.getBytes(Charset.defaultCharset()));
5028    } catch (CryptoException e) {
5029  0 String errorMsg = "Error while encrypting the password. " + e.getMessage();
5030  0 throw new APIManagementException(errorMsg, e);
5031    }
5032    }
5033   
5034    /**
5035    * Search Apis by Doc Content
5036    *
5037    * @param registry - Registry which is searched
5038    * @param tenantID - Tenant id of logged in domain
5039    * @param username - Logged in username
5040    * @param searchTerm - Search value for doc
5041    * @param searchClient - Search client
5042    * @return - Documentation to APIs map
5043    * @throws APIManagementException - If failed to get ArtifactManager for given tenant
5044    */
 
5045  0 toggle public static Map<Documentation, API> searchAPIsByDoc(Registry registry, int tenantID, String username,
5046    String searchTerm, String searchClient) throws APIManagementException {
5047  0 Map<Documentation, API> apiDocMap = new HashMap<Documentation, API>();
5048   
5049  0 try {
5050  0 PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(username);
5051  0 GenericArtifactManager artifactManager = APIUtil.getArtifactManager(registry,
5052    APIConstants.API_KEY);
5053  0 if (artifactManager == null) {
5054  0 String errorMessage = "Artifact manager is null when searching APIs by docs in tenant ID " + tenantID;
5055  0 log.error(errorMessage);
5056  0 throw new APIManagementException(errorMessage);
5057    }
5058  0 GenericArtifactManager docArtifactManager = APIUtil.getArtifactManager(registry,
5059    APIConstants.DOCUMENTATION_KEY);
5060  0 if (docArtifactManager == null) {
5061  0 String errorMessage = "Doc artifact manager is null when searching APIs by docs in tenant ID " +
5062    tenantID;
5063  0 log.error(errorMessage);
5064  0 throw new APIManagementException(errorMessage);
5065    }
5066  0 SolrClient client = SolrClient.getInstance();
5067  0 Map<String, String> fields = new HashMap<String, String>();
5068  0 fields.put(APIConstants.DOCUMENTATION_SEARCH_PATH_FIELD, "*" + APIConstants.API_ROOT_LOCATION + "*");
5069  0 fields.put(APIConstants.DOCUMENTATION_SEARCH_MEDIA_TYPE_FIELD, "*");
5070   
5071  0 if (tenantID == -1) {
5072  0 tenantID = MultitenantConstants.SUPER_TENANT_ID;
5073    }
5074    //PaginationContext.init(0, 10000, "ASC", APIConstants.DOCUMENTATION_SEARCH_PATH_FIELD, Integer.MAX_VALUE);
5075  0 SolrDocumentList documentList = client.query(searchTerm, tenantID, fields);
5076   
5077  0 org.wso2.carbon.user.api.AuthorizationManager manager = ServiceReferenceHolder.getInstance().
5078    getRealmService().getTenantUserRealm(tenantID).
5079    getAuthorizationManager();
5080   
5081  0 username = MultitenantUtils.getTenantAwareUsername(username);
5082   
5083  0 for (SolrDocument document : documentList) {
5084  0 String filePath = (String) document.getFieldValue("path_s");
5085  0 int index = filePath.indexOf(APIConstants.APIMGT_REGISTRY_LOCATION);
5086  0 filePath = filePath.substring(index);
5087  0 Association[] associations = registry.getAllAssociations(filePath);
5088  0 API api = null;
5089  0 Documentation doc = null;
5090  0 for (Association association : associations) {
5091  0 boolean isAuthorized;
5092  0 String documentationPath = association.getSourcePath();
5093  0 String path = RegistryUtils.getAbsolutePath(RegistryContext.getBaseInstance(),
5094    APIUtil.getMountedPath(RegistryContext.getBaseInstance(),
5095    RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH) + documentationPath);
5096  0 if (CarbonConstants.REGISTRY_ANONNYMOUS_USERNAME.equalsIgnoreCase(username)) {
5097  0 isAuthorized = manager.isRoleAuthorized(APIConstants.ANONYMOUS_ROLE, path, ActionConstants.GET);
5098    } else {
5099  0 isAuthorized = manager.isUserAuthorized(username, path, ActionConstants.GET);
5100    }
5101   
5102  0 if (isAuthorized) {
5103  0 Resource docResource = registry.get(documentationPath);
5104  0 String docArtifactId = docResource.getUUID();
5105  0 if (docArtifactId != null) {
5106  0 GenericArtifact docArtifact = docArtifactManager.getGenericArtifact(docArtifactId);
5107  0 doc = APIUtil.getDocumentation(docArtifact);
5108    }
5109   
5110  0 Association[] docAssociations = registry.getAssociations(documentationPath, APIConstants.DOCUMENTATION_ASSOCIATION);
5111    /* There will be only one document association, for a document path which is by its owner API*/
5112  0 if (docAssociations.length > 0) {
5113   
5114  0 String apiPath = docAssociations[0].getSourcePath();
5115  0 path = RegistryUtils.getAbsolutePath(RegistryContext.getBaseInstance(),
5116    APIUtil.getMountedPath(RegistryContext.getBaseInstance(),
5117    RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH) + apiPath);
5118  0 if (CarbonConstants.REGISTRY_ANONNYMOUS_USERNAME.equalsIgnoreCase(username)) {
5119  0 isAuthorized = manager.isRoleAuthorized(APIConstants.ANONYMOUS_ROLE, path, ActionConstants.GET);
5120    } else {
5121  0 isAuthorized = manager.isUserAuthorized(username, path, ActionConstants.GET);
5122    }
5123   
5124  0 if (isAuthorized) {
5125  0 Resource resource = registry.get(apiPath);
5126  0 String apiArtifactId = resource.getUUID();
5127  0 if (apiArtifactId != null) {
5128  0 GenericArtifact apiArtifact = artifactManager.getGenericArtifact(apiArtifactId);
5129  0 api = APIUtil.getAPI(apiArtifact, registry);
5130    } else {
5131  0 throw new GovernanceException("artifact id is null of " + apiPath);
5132    }
5133    }
5134    }
5135    }
5136   
5137  0 if (doc != null && api != null) {
5138  0 if (APIConstants.STORE_CLIENT.equals(searchClient)) {
5139  0 if (APIConstants.PUBLISHED.equals(api.getStatus()) ||
5140    APIConstants.PROTOTYPED.equals(api.getStatus())) {
5141  0 apiDocMap.put(doc, api);
5142    }
5143    } else {
5144  0 apiDocMap.put(doc, api);
5145    }
5146    }
5147    }
5148    }
5149    } catch (IndexerException e) {
5150  0 handleException("Failed to search APIs with type Doc", e);
5151    } catch (RegistryException e) {
5152  0 handleException("Failed to search APIs with type Doc", e);
5153    } catch (UserStoreException e) {
5154  0 handleException("Failed to search APIs with type Doc", e);
5155    }
5156  0 return apiDocMap;
5157    }
5158   
5159   
 
5160  0 toggle public static Map<String, Object> searchAPIsByURLPattern(Registry registry, String searchTerm, int start, int end)
5161    throws APIManagementException {
5162  0 SortedSet<API> apiSet = new TreeSet<API>(new APINameComparator());
5163  0 List<API> apiList = new ArrayList<API>();
5164  0 final String searchValue = searchTerm.trim();
5165  0 Map<String, Object> result = new HashMap<String, Object>();
5166  0 int totalLength = 0;
5167  0 String criteria;
5168  0 Map<String, List<String>> listMap = new HashMap<String, List<String>>();
5169  0 GenericArtifact[] genericArtifacts = new GenericArtifact[0];
5170  0 GenericArtifactManager artifactManager = null;
5171  0 try {
5172  0 artifactManager = APIUtil.getArtifactManager(registry, APIConstants.API_KEY);
5173  0 if (artifactManager == null) {
5174  0 String errorMessage = "Artifact manager is null when searching APIs by URL pattern " + searchTerm;
5175  0 log.error(errorMessage);
5176  0 throw new APIManagementException(errorMessage);
5177    }
5178  0 PaginationContext.init(0, 10000, "ASC", APIConstants.API_OVERVIEW_NAME, Integer.MAX_VALUE);
5179  0 if (artifactManager != null) {
5180  0 for (int i = 0; i < 20; i++) { //This need to fix in future.We don't have a way to get max value of
5181    // "url_template" entry stores in registry,unless we search in each API
5182  0 criteria = APIConstants.API_URI_PATTERN + i;
5183  0 listMap.put(criteria, new ArrayList<String>() {
 
5184  0 toggle {
5185  0 add(searchValue);
5186    }
5187    });
5188  0 genericArtifacts = (GenericArtifact[]) ArrayUtils.addAll(genericArtifacts, artifactManager
5189    .findGenericArtifacts(listMap));
5190    }
5191  0 if (genericArtifacts == null || genericArtifacts.length == 0) {
5192  0 result.put("apis", apiSet);
5193  0 result.put("length", 0);
5194  0 return result;
5195    }
5196  0 totalLength = genericArtifacts.length;
5197  0 StringBuilder apiNames = new StringBuilder();
5198  0 for (GenericArtifact artifact : genericArtifacts) {
5199  0 if (artifact == null) {
5200  0 log.error("Failed to retrieve an artifact when searching APIs by URL pattern : " + searchTerm +
5201    " , continuing with next artifact.");
5202  0 continue;
5203    }
5204  0 if (apiNames.indexOf(artifact.getAttribute(APIConstants.API_OVERVIEW_NAME)) < 0) {
5205  0 String status = APIUtil.getLcStateFromArtifact(artifact);
5206  0 if (isAllowDisplayAPIsWithMultipleStatus()) {
5207  0 if (APIConstants.PUBLISHED.equals(status) || APIConstants.DEPRECATED.equals(status)) {
5208  0 API api = APIUtil.getAPI(artifact, registry);
5209  0 if (api != null) {
5210  0 apiList.add(api);
5211  0 apiNames.append(api.getId().getApiName());
5212    }
5213    }
5214    } else {
5215  0 if (APIConstants.PUBLISHED.equals(status)) {
5216  0 API api = APIUtil.getAPI(artifact, registry);
5217  0 if (api != null) {
5218  0 apiList.add(api);
5219  0 apiNames.append(api.getId().getApiName());
5220    }
5221    }
5222    }
5223    }
5224  0 totalLength = apiList.size();
5225    }
5226  0 if (totalLength <= ((start + end) - 1)) {
5227  0 end = totalLength;
5228    }
5229  0 for (int i = start; i < end; i++) {
5230  0 apiSet.add(apiList.get(i));
5231    }
5232    }
5233    } catch (APIManagementException e) {
5234  0 handleException("Failed to search APIs with input url-pattern", e);
5235    } catch (GovernanceException e) {
5236  0 handleException("Failed to search APIs with input url-pattern", e);
5237    }
5238  0 result.put("apis", apiSet);
5239  0 result.put("length", totalLength);
5240  0 return result;
5241    }
5242   
5243    /**
5244    * This method will check the validity of given url. WSDL url should be
5245    * contain http, https or file system patch
5246    * otherwise we will mark it as invalid wsdl url. How ever here we do not
5247    * validate wsdl content.
5248    *
5249    * @param wsdlURL wsdl url tobe tested
5250    * @return true if its valid url else fale
5251    */
 
5252  251 toggle public static boolean isValidWSDLURL(String wsdlURL, boolean required) {
5253  251 if (wsdlURL != null && !"".equals(wsdlURL)) {
5254  2 if (wsdlURL.startsWith("http:") || wsdlURL.startsWith("https:") ||
5255    wsdlURL.startsWith("file:") || wsdlURL.startsWith("/registry")) {
5256  2 return true;
5257    }
5258  249 } else if (!required) {
5259    // If the WSDL in not required and URL is empty, then we don't need
5260    // to add debug log.
5261    // Hence returning.
5262  249 return false;
5263    }
5264   
5265  0 if (log.isDebugEnabled()) {
5266  0 log.debug("WSDL url validation failed. Provided wsdl url is not valid url: " + wsdlURL);
5267    }
5268  0 return false;
5269    }
5270   
5271    /**
5272    * load tenant axis configurations.
5273    *
5274    * @param tenantDomain
5275    */
 
5276  0 toggle public static void loadTenantConfig(String tenantDomain) {
5277  0 final String finalTenantDomain = tenantDomain;
5278  0 ConfigurationContext ctx =
5279    ServiceReferenceHolder.getContextService().getServerConfigContext();
5280   
5281    //Cannot use the tenantDomain directly because it's getting locked in createTenantConfigurationContext()
5282    // method in TenantAxisUtils
5283  0 String accessFlag = tenantDomain + "@WSO2";
5284   
5285  0 long lastAccessed = TenantAxisUtils.getLastAccessed(tenantDomain, ctx);
5286    //Only if the tenant is in unloaded state, we do the loading
5287  0 if (System.currentTimeMillis() - lastAccessed >= tenantIdleTimeMillis) {
5288  0 synchronized (accessFlag.intern()) {
5289    // Currently loading tenants are added to a set.
5290    // If a tenant domain is in the set it implies that particular tenant is being loaded.
5291    // Therefore if and only if the set does not contain the tenant.
5292  0 if (!currentLoadingTenants.contains(tenantDomain)) {
5293    //Only one concurrent request is allowed to add to the currentLoadingTenants
5294  0 currentLoadingTenants.add(tenantDomain);
5295  0 ctx.getThreadPool().execute(new Runnable() {
 
5296  0 toggle @Override
5297    public void run() {
5298  0 Thread.currentThread().setName("APIMHostObjectUtils-loadTenantConfig-thread");
5299  0 try {
5300  0 PrivilegedCarbonContext.startTenantFlow();
5301  0 PrivilegedCarbonContext.getThreadLocalCarbonContext()
5302    .setTenantDomain(finalTenantDomain, true);
5303  0 ConfigurationContext ctx = ServiceReferenceHolder.getContextService()
5304    .getServerConfigContext();
5305  0 TenantAxisUtils.getTenantAxisConfiguration(finalTenantDomain, ctx);
5306    } catch (Exception e) {
5307  0 log.error("Error while creating axis configuration for tenant " + finalTenantDomain, e);
5308    } finally {
5309    //only after the tenant is loaded completely, the tenant domain is removed from the set
5310  0 currentLoadingTenants.remove(finalTenantDomain);
5311  0 PrivilegedCarbonContext.endTenantFlow();
5312    }
5313    }
5314    });
5315    }
5316    }
5317    }
5318    }
5319   
5320    /**
5321    * load tenant axis configurations.
5322    *
5323    * @param tenantDomain
5324    */
 
5325  14 toggle public static void loadTenantConfigBlockingMode(String tenantDomain) {
5326   
5327  14 try {
5328  14 ConfigurationContext ctx = ServiceReferenceHolder.getContextService().getServerConfigContext();
5329  14 TenantAxisUtils.getTenantAxisConfiguration(tenantDomain, ctx);
5330    } catch (Exception e) {
5331  0 log.error("Error while creating axis configuration for tenant " + tenantDomain, e);
5332    }
5333    }
5334   
 
5335  0 toggle public static String extractCustomerKeyFromAuthHeader(Map headersMap) {
5336   
5337    //From 1.0.7 version of this component onwards remove the OAuth authorization header from
5338    // the message is configurable. So we dont need to remove headers at this point.
5339  0 String authHeader = (String) headersMap.get(HttpHeaders.AUTHORIZATION);
5340  0 if (authHeader == null) {
5341  0 return null;
5342    }
5343   
5344  0 if (authHeader.startsWith("OAuth ") || authHeader.startsWith("oauth ")) {
5345  0 authHeader = authHeader.substring(authHeader.indexOf("o"));
5346    }
5347   
5348  0 String[] headers = authHeader.split(APIConstants.OAUTH_HEADER_SPLITTER);
5349  0 for (String header : headers) {
5350  0 String[] elements = header.split(APIConstants.CONSUMER_KEY_SEGMENT_DELIMITER);
5351  0 if (elements.length > 1) {
5352  0 int j = 0;
5353  0 boolean isConsumerKeyHeaderAvailable = false;
5354  0 for (String element : elements) {
5355  0 if (!"".equals(element.trim())) {
5356  0 if (APIConstants.CONSUMER_KEY_SEGMENT.equals(elements[j].trim())) {
5357  0 isConsumerKeyHeaderAvailable = true;
5358  0 } else if (isConsumerKeyHeaderAvailable) {
5359  0 return removeLeadingAndTrailing(elements[j].trim());
5360    }
5361    }
5362  0 j++;
5363    }
5364    }
5365    }
5366  0 return null;
5367    }
5368   
 
5369  0 toggle private static String removeLeadingAndTrailing(String base) {
5370  0 String result = base;
5371   
5372  0 if (base.startsWith("\"") || base.endsWith("\"")) {
5373  0 result = base.replace("\"", "");
5374    }
5375  0 return result.trim();
5376    }
5377   
5378    /**
5379    * This method will return mounted path of the path if the path
5380    * is mounted. Else path will be returned.
5381    *
5382    * @param registryContext Registry Context instance which holds path mappings
5383    * @param path default path of the registry
5384    * @return mounted path or path
5385    */
 
5386  1820 toggle public static String getMountedPath(RegistryContext registryContext, String path) {
5387  1820 if (registryContext != null && path != null) {
5388  1820 List<Mount> mounts = registryContext.getMounts();
5389  1820 if (mounts != null) {
5390  1820 for (Mount mount : mounts) {
5391  0 if (path.equals(mount.getPath())) {
5392  0 return mount.getTargetPath();
5393    }
5394    }
5395    }
5396    }
5397  1820 return path;
5398    }
5399   
5400    /**
5401    * Returns a map of gateway / store domains for the tenant
5402    *
5403    * @return a Map of domain names for tenant
5404    * @throws org.wso2.carbon.apimgt.api.APIManagementException if an error occurs when loading tiers from the registry
5405    */
 
5406  26 toggle public static Map<String, String> getDomainMappings(String tenantDomain, String appType)
5407    throws APIManagementException {
5408  26 Map<String, String> domains = new HashMap<String, String>();
5409  26 String resourcePath;
5410  26 try {
5411  26 Registry registry = ServiceReferenceHolder.getInstance().getRegistryService().
5412    getGovernanceSystemRegistry();
5413  26 resourcePath = APIConstants.API_DOMAIN_MAPPINGS.replace("<tenant-id>", tenantDomain);
5414  26 if (registry.resourceExists(resourcePath)) {
5415  0 Resource resource = registry.get(resourcePath);
5416  0 String content = new String((byte[]) resource.getContent(), Charset.defaultCharset());
5417  0 JSONParser parser = new JSONParser();
5418  0 JSONObject mappings = (JSONObject) parser.parse(content);
5419  0 if (mappings.get(appType) != null) {
5420  0 mappings = (JSONObject) mappings.get(appType);
5421  0 for (Object o : mappings.entrySet()) {
5422  0 Entry thisEntry = (Entry) o;
5423  0 String key = (String) thisEntry.getKey();
5424    //Instead strictly comparing customUrl, checking whether name is starting with customUrl
5425    //to allow users to add multiple URLs if needed
5426  0 if (!StringUtils.isEmpty(key) && key.startsWith(APIConstants.CUSTOM_URL)) {
5427  0 String value = (String) thisEntry.getValue();
5428  0 domains.put(key, value);
5429    }
5430    }
5431    }
5432    }
5433    } catch (RegistryException e) {
5434  0 String msg = "Error while retrieving gateway domain mappings from registry";
5435  0 log.error(msg, e);
5436  0 throw new APIManagementException(msg, e);
5437    } catch (ClassCastException e) {
5438  0 String msg = "Invalid JSON found in the gateway tenant domain mappings";
5439  0 log.error(msg, e);
5440  0 throw new APIManagementException(msg, e);
5441    } catch (ParseException e) {
5442  0 String msg = "Malformed JSON found in the gateway tenant domain mappings";
5443  0 log.error(msg, e);
5444  0 throw new APIManagementException(msg, e);
5445    }
5446  26 return domains;
5447    }
5448   
5449    /**
5450    * This method used to Downloaded Uploaded Documents from publisher
5451    *
5452    * @param userName logged in username
5453    * @param resourceUrl resource want to download
5454    * @param tenantDomain loggedUserTenantDomain
5455    * @return map that contains Data of the resource
5456    * @throws APIManagementException
5457    */
 
5458  0 toggle public static Map<String, Object> getDocument(String userName, String resourceUrl, String tenantDomain)
5459    throws APIManagementException {
5460  0 Map<String, Object> documentMap = new HashMap<String, Object>();
5461   
5462  0 InputStream inStream = null;
5463  0 String[] resourceSplitPath =
5464    resourceUrl.split(RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH);
5465  0 if (resourceSplitPath.length == 2) {
5466  0 resourceUrl = resourceSplitPath[1];
5467    } else {
5468  0 handleException("Invalid resource Path " + resourceUrl);
5469    }
5470  0 Resource apiDocResource;
5471  0 Registry registryType = null;
5472  0 boolean isTenantFlowStarted = false;
5473  0 try {
5474  0 int tenantId;
5475  0 if (tenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
5476  0 PrivilegedCarbonContext.startTenantFlow();
5477  0 isTenantFlowStarted = true;
5478   
5479  0 PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
5480  0 tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
5481    } else {
5482  0 tenantId = MultitenantConstants.SUPER_TENANT_ID;
5483    }
5484   
5485  0 userName = MultitenantUtils.getTenantAwareUsername(userName);
5486  0 registryType = ServiceReferenceHolder
5487    .getInstance().
5488    getRegistryService().getGovernanceUserRegistry(userName, tenantId);
5489  0 if (registryType.resourceExists(resourceUrl)) {
5490  0 apiDocResource = registryType.get(resourceUrl);
5491  0 inStream = apiDocResource.getContentStream();
5492  0 documentMap.put("Data", inStream);
5493  0 documentMap.put("contentType", apiDocResource.getMediaType());
5494  0 String[] content = apiDocResource.getPath().split("/");
5495  0 documentMap.put("name", content[content.length - 1]);
5496    }
5497    } catch (RegistryException e) {
5498  0 String msg = "Couldn't retrieve registry for User " + userName + " Tenant " + tenantDomain;
5499  0 log.error(msg, e);
5500  0 handleException(msg, e);
5501    } finally {
5502  0 if (isTenantFlowStarted) {
5503  0 PrivilegedCarbonContext.endTenantFlow();
5504    }
5505    }
5506  0 return documentMap;
5507    }
5508   
5509    /**
5510    * this method used to set environments values to api object.
5511    *
5512    * @param environments environments values in json format
5513    * @return set of environments that Published
5514    */
 
5515  4160 toggle public static Set<String> extractEnvironmentsForAPI(String environments) {
5516  4160 Set<String> environmentStringSet = null;
5517  4160 if (environments == null) {
5518  91 environmentStringSet = new HashSet<String>(
5519    ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService()
5520    .getAPIManagerConfiguration().getApiGatewayEnvironments().keySet());
5521    } else {
5522    //handle not to publish to any of the gateways
5523  4069 if (APIConstants.API_GATEWAY_NONE.equals(environments)) {
5524  0 environmentStringSet = new HashSet<String>();
5525    }
5526    //handle to set published gateways nto api object
5527  4069 else if (!"".equals(environments)) {
5528  4069 String[] publishEnvironmentArray = environments.split(",");
5529  4069 environmentStringSet = new HashSet<String>(Arrays.asList(publishEnvironmentArray));
5530  4069 environmentStringSet.remove(APIConstants.API_GATEWAY_NONE);
5531    }
5532    //handle to publish to any of the gateways when api creating stage
5533  0 else if ("".equals(environments)) {
5534  0 environmentStringSet = new HashSet<String>(
5535    ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService()
5536    .getAPIManagerConfiguration().getApiGatewayEnvironments().keySet());
5537    }
5538    }
5539  4160 return environmentStringSet;
5540    }
5541   
5542    /**
5543    * This method used to set environment values to governance artifact of API .
5544    *
5545    * @param api API object with the attributes value
5546    */
 
5547  671 toggle public static String writeEnvironmentsToArtifact(API api) {
5548  671 StringBuilder publishedEnvironments = new StringBuilder();
5549  671 Set<String> apiEnvironments = api.getEnvironments();
5550  671 if (apiEnvironments != null) {
5551  658 for (String environmentName : apiEnvironments) {
5552  659 publishedEnvironments.append(environmentName).append(',');
5553    }
5554   
5555  658 if (apiEnvironments.isEmpty()) {
5556  0 publishedEnvironments.append("none,");
5557    }
5558   
5559  658 if (!publishedEnvironments.toString().isEmpty()) {
5560  658 publishedEnvironments.deleteCharAt(publishedEnvironments.length() - 1);
5561    }
5562    }
5563  671 return publishedEnvironments.toString();
5564    }
5565   
5566    /**
5567    * This method used to get the currently published gateway environments of an API .
5568    *
5569    * @param api API object with the attributes value
5570    */
 
5571  1 toggle public static List<Environment> getEnvironmentsOfAPI(API api) {
5572  1 Map<String, Environment> gatewayEnvironments = ServiceReferenceHolder.getInstance()
5573    .getAPIManagerConfigurationService()
5574    .getAPIManagerConfiguration()
5575    .getApiGatewayEnvironments();
5576  1 Set<String> apiEnvironments = api.getEnvironments();
5577  1 List<Environment> returnEnvironments = new ArrayList<Environment>();
5578   
5579  1 for (Environment environment : gatewayEnvironments.values()) {
5580  1 for (String apiEnvironment : apiEnvironments) {
5581  1 if (environment.getName().equals(apiEnvironment)) {
5582  1 returnEnvironments.add(environment);
5583  1 break;
5584    }
5585    }
5586    }
5587  1 return returnEnvironments;
5588    }
5589   
5590    /**
5591    * Given the apps and the application name to check for, it will check if the application already exists.
5592    *
5593    * @param apps The collection of applications
5594    * @param name The application to be checked if exists
5595    * @return true - if an application of the name <name> already exists in the collection <apps>
5596    * false- if an application of the name <name> does not already exists in the collection <apps>
5597    */
 
5598  0 toggle public static boolean doesApplicationExist(Application[] apps, String name) {
5599  0 boolean doesApplicationExist = false;
5600  0 if (apps != null) {
5601  0 for (Application app : apps) {
5602  0 if (app.getName().equals(name)) {
5603  0 doesApplicationExist = true;
5604    }
5605    }
5606    }
5607  0 return doesApplicationExist;
5608    }
5609   
5610    /**
5611    * Read the group id extractor class reference from api-manager.xml.
5612    *
5613    * @return group id extractor class reference.
5614    */
 
5615  403 toggle public static String getGroupingExtractorImplementation() {
5616  403 APIManagerConfiguration config = ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService()
5617    .getAPIManagerConfiguration();
5618  403 return config.getFirstProperty(APIConstants.API_STORE_GROUP_EXTRACTOR_IMPLEMENTATION);
5619    }
5620   
5621    /**
5622    * This method will update the permission cache of the tenant which is related to the given usename
5623    *
5624    * @param username User name to find the relevant tenant
5625    * @throws UserStoreException if the permission update failed
5626    */
 
5627  0 toggle public static void updatePermissionCache(String username) throws UserStoreException {
5628  0 String tenantDomain = MultitenantUtils.getTenantDomain(username);
5629  0 int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager().getTenantId(tenantDomain);
5630  0 PermissionUpdateUtil.updatePermissionTree(tenantId);
5631    }
5632   
5633    /**
5634    * Check whether given application name is available under current subscriber or group
5635    *
5636    * @param subscriber subscriber name
5637    * @param applicationName application name
5638    * @param groupId group of the subscriber
5639    * @return true if application is available for the subscriber
5640    * @throws APIManagementException if failed to get applications for given subscriber
5641    */
 
5642  152 toggle public static boolean isApplicationExist(String subscriber, String applicationName, String groupId)
5643    throws APIManagementException {
5644  152 return ApiMgtDAO.getInstance().isApplicationExist(applicationName, subscriber, groupId);
5645    }
5646   
 
5647  192 toggle public static String getHostAddress() {
5648   
5649  192 if (hostAddress != null) {
5650  179 return hostAddress;
5651    }
5652  13 hostAddress = ServerConfiguration.getInstance().getFirstProperty(APIConstants.API_MANAGER_HOSTNAME);
5653  13 if (null == hostAddress) {
5654  13 if (getLocalAddress() != null) {
5655  13 hostAddress = getLocalAddress().getHostName();
5656    }
5657  13 if (hostAddress == null) {
5658  0 hostAddress = APIConstants.API_MANAGER_HOSTNAME_UNKNOWN;
5659    }
5660  13 return hostAddress;
5661    } else {
5662  0 return hostAddress;
5663    }
5664    }
5665   
 
5666  26 toggle private static InetAddress getLocalAddress() {
5667  26 Enumeration<NetworkInterface> ifaces = null;
5668  26 try {
5669  26 ifaces = NetworkInterface.getNetworkInterfaces();
5670    } catch (SocketException e) {
5671  0 log.error("Failed to get host address", e);
5672    }
5673  26 if (ifaces != null) {
5674  26 while (ifaces.hasMoreElements()) {
5675  26 NetworkInterface iface = ifaces.nextElement();
5676  26 Enumeration<InetAddress> addresses = iface.getInetAddresses();
5677   
5678  26 while (addresses.hasMoreElements()) {
5679  26 InetAddress addr = addresses.nextElement();
5680  26 if (addr instanceof Inet4Address && !addr.isLoopbackAddress()) {
5681  26 return addr;
5682    }
5683    }
5684    }
5685    }
5686   
5687  0 return null;
5688    }
5689   
 
5690  0 toggle public static boolean isStringArray(Object[] args) {
5691   
5692  0 for (Object arg : args) {
5693  0 if (!(arg instanceof String)) {
5694  0 return false;
5695    }
5696    }
5697  0 return true;
5698    }
5699   
 
5700  0 toggle public static String appendDomainWithUser(String username, String domain) {
5701  0 if (username.contains(APIConstants.EMAIL_DOMAIN_SEPARATOR) || username.contains(APIConstants.EMAIL_DOMAIN_SEPARATOR_REPLACEMENT) || MultitenantConstants.SUPER_TENANT_NAME.equalsIgnoreCase(username)) {
5702  0 return username;
5703    }
5704  0 return username + APIConstants.EMAIL_DOMAIN_SEPARATOR + domain;
5705    }
5706   
5707    /*
5708    * Util method to convert a java object to a json object
5709    *
5710    */
 
5711  10 toggle public static String convertToString(Object obj) {
5712  10 Gson gson = new Gson();
5713  10 return gson.toJson(obj);
5714    }
5715   
5716   
 
5717  303 toggle public static String getSequencePath(APIIdentifier identifier, String pathFlow) {
5718  303 String artifactPath = APIConstants.API_ROOT_LOCATION + RegistryConstants.PATH_SEPARATOR +
5719    identifier.getProviderName() + RegistryConstants.PATH_SEPARATOR +
5720    identifier.getApiName() + RegistryConstants.PATH_SEPARATOR + identifier.getVersion();
5721  303 return artifactPath + RegistryConstants.PATH_SEPARATOR + pathFlow + RegistryConstants.PATH_SEPARATOR;
5722    }
5723   
 
5724  1915 toggle private static String getAPIMonetizationCategory(Set<Tier> tiers, String tenantDomain)
5725    throws APIManagementException {
5726  1915 boolean isPaidFound = false;
5727  1915 boolean isFreeFound = false;
5728  1915 for (Tier tier : tiers) {
5729  2724 if (isTierPaid(tier.getName(), tenantDomain)) {
5730  0 isPaidFound = true;
5731    } else {
5732  2724 isFreeFound = true;
5733   
5734  2724 if (isPaidFound) {
5735  0 break;
5736    }
5737    }
5738    }
5739   
5740  1915 if (!isPaidFound) {
5741  1915 return APIConstants.API_CATEGORY_FREE;
5742  0 } else if (!isFreeFound) {
5743  0 return APIConstants.API_CATEGORY_PAID;
5744    } else {
5745  0 return APIConstants.API_CATEGORY_FREEMIUM;
5746    }
5747    }
5748   
 
5749  2724 toggle private static boolean isTierPaid(String tierName, String tenantDomainName) throws APIManagementException {
5750  2724 String tenantDomain = tenantDomainName;
5751  2724 if (tenantDomain == null) {
5752  0 tenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
5753    }
5754  2724 if (APIConstants.UNLIMITED_TIER.equalsIgnoreCase(tierName)) {
5755  781 return isUnlimitedTierPaid(tenantDomain);
5756    }
5757   
5758  1943 boolean isPaid = false;
5759  1943 Tier tier = getTierFromCache(tierName, tenantDomain);
5760   
5761  1943 if (tier != null) {
5762  1943 final Map<String, Object> tierAttributes = tier.getTierAttributes();
5763   
5764  1943 if (tierAttributes != null) {
5765  31 String isPaidValue = tier.getTierPlan();
5766   
5767  31 if (isPaidValue != null && APIConstants.COMMERCIAL_TIER_PLAN.equals(isPaidValue)) {
5768  0 isPaid = true;
5769    }
5770    }
5771    } else {
5772  0 throw new APIManagementException("Tier " + tierName + "cannot be found");
5773    }
5774  1943 return isPaid;
5775    }
5776   
 
5777  4029 toggle private static boolean isUnlimitedTierPaid(String tenantDomain) throws APIManagementException {
5778  4029 JSONObject apiTenantConfig = null;
5779  4029 try {
5780  4029 String content = null;
5781   
5782  4029 PrivilegedCarbonContext.startTenantFlow();
5783  4029 PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
5784   
5785  4029 int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager()
5786    .getTenantId(tenantDomain);
5787  4029 Registry registry = ServiceReferenceHolder.getInstance().getRegistryService()
5788    .getConfigSystemRegistry(tenantId);
5789   
5790  4029 if (registry.resourceExists(APIConstants.API_TENANT_CONF_LOCATION)) {
5791  4029 Resource resource = registry.get(APIConstants.API_TENANT_CONF_LOCATION);
5792  4029 content = new String((byte[]) resource.getContent(), Charset.defaultCharset());
5793    }
5794   
5795  4029 if (content != null) {
5796  4029 JSONParser parser = new JSONParser();
5797  4029 apiTenantConfig = (JSONObject) parser.parse(content);
5798    }
5799    } catch (UserStoreException e) {
5800  0 handleException("UserStoreException thrown when getting API tenant config from registry", e);
5801    } catch (RegistryException e) {
5802  0 handleException("RegistryException thrown when getting API tenant config from registry", e);
5803    } catch (ParseException e) {
5804  0 handleException("ParseException thrown when passing API tenant config from registry", e);
5805    } finally {
5806  4029 PrivilegedCarbonContext.endTenantFlow();
5807    }
5808   
5809  4029 if (apiTenantConfig != null) {
5810  4029 Object value = apiTenantConfig.get(APIConstants.API_TENANT_CONF_IS_UNLIMITED_TIER_PAID);
5811   
5812  4029 if (value != null) {
5813  4029 return Boolean.parseBoolean(value.toString());
5814    } else {
5815  0 throw new APIManagementException(APIConstants.API_TENANT_CONF_IS_UNLIMITED_TIER_PAID
5816    + " config does not exist for tenant " + tenantDomain);
5817    }
5818    }
5819   
5820  0 return false;
5821    }
5822   
 
5823  1963 toggle public static Tier getTierFromCache(String tierName, String tenantDomain) throws APIManagementException {
5824  1963 Map<String, Tier> tierMap = null;
5825   
5826  1963 try {
5827  1963 PrivilegedCarbonContext.startTenantFlow();
5828  1963 PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
5829   
5830  1963 if (getTiersCache().containsKey(tierName)) {
5831  1875 tierMap = (Map<String, Tier>) getTiersCache().get(tierName);
5832    } else {
5833  88 int requestedTenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
5834  88 if (!APIUtil.isAdvanceThrottlingEnabled()) {
5835  31 if (requestedTenantId == 0) {
5836  0 tierMap = APIUtil.getTiers();
5837    } else {
5838  31 tierMap = APIUtil.getTiers(requestedTenantId);
5839    }
5840    } else {
5841  57 if (requestedTenantId == 0) {
5842  0 tierMap = APIUtil.getAdvancedSubsriptionTiers();
5843    } else {
5844  57 tierMap = APIUtil.getAdvancedSubsriptionTiers(requestedTenantId);
5845    }
5846    }
5847  88 getTiersCache().put(tierName, tierMap);
5848    }
5849    } finally {
5850  1963 PrivilegedCarbonContext.endTenantFlow();
5851    }
5852   
5853  1963 return tierMap.get(tierName);
5854    }
5855   
5856   
 
5857  13 toggle public static void clearTiersCache(String tenantDomain) {
5858  13 try {
5859  13 PrivilegedCarbonContext.startTenantFlow();
5860  13 PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
5861   
5862  13 getTiersCache().removeAll();
5863    } finally {
5864  13 PrivilegedCarbonContext.endTenantFlow();
5865    }
5866    }
5867   
 
5868  3939 toggle private static Cache getTiersCache() {
5869  3939 return Caching.getCacheManager(APIConstants.API_MANAGER_CACHE_MANAGER).
5870    getCache(APIConstants.TIERS_CACHE);
5871    }
5872   
5873    /**
5874    * Util method to return the artifact from a registry resource path
5875    *
5876    * @param apiIdentifier
5877    * @param registry
5878    * @return
5879    * @throws APIManagementException
5880    */
 
5881  445 toggle public static GenericArtifact getAPIArtifact(APIIdentifier apiIdentifier, Registry registry)
5882    throws APIManagementException {
5883  445 String apiPath = APIUtil.getAPIPath(apiIdentifier);
5884  445 GenericArtifactManager artifactManager = APIUtil.getArtifactManager(registry, APIConstants.API_KEY);
5885  445 if (artifactManager == null) {
5886  0 String errorMessage = "Artifact manager is null when getting generic artifact for API " +
5887    apiIdentifier.getApiName();
5888  0 log.error(errorMessage);
5889  0 throw new APIManagementException(errorMessage);
5890    }
5891  445 try {
5892  445 Resource apiResource = registry.get(apiPath);
5893  445 String artifactId = apiResource.getUUID();
5894  445 if (artifactId == null) {
5895  0 throw new APIManagementException("artifact id is null for : " + apiPath);
5896    }
5897  445 return artifactManager.getGenericArtifact(artifactId);
5898    } catch (RegistryException e) {
5899  0 handleException("Failed to get API artifact from : " + apiPath, e);
5900  0 return null;
5901    }
5902    }
5903   
5904    /**
5905    * Return a http client instance
5906    *
5907    * @param port - server port
5908    * @param protocol- service endpoint protocol http/https
5909    * @return
5910    */
 
5911  144 toggle public static HttpClient getHttpClient(int port, String protocol) {
5912  145 SchemeRegistry registry = new SchemeRegistry();
5913  144 SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
5914  145 String hostnameVerifierOption = System.getProperty(HOST_NAME_VERIFIER);
5915  145 String sslValue = null;
5916   
5917  145 AxisConfiguration axis2Config = ServiceReferenceHolder.getContextService().getServerConfigContext()
5918    .getAxisConfiguration();
5919  145 org.apache.axis2.description.Parameter sslVerifyClient = axis2Config.getTransportIn(APIConstants.HTTPS_PROTOCOL)
5920    .getParameter(APIConstants.SSL_VERIFY_CLIENT);
5921  145 if (sslVerifyClient != null) {
5922  4 sslValue = (String) sslVerifyClient.getValue();
5923    }
5924   
5925  145 X509HostnameVerifier hostnameVerifier;
5926  145 if (ALLOW_ALL.equalsIgnoreCase(hostnameVerifierOption)) {
5927  145 hostnameVerifier = SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
5928  0 } else if (STRICT.equalsIgnoreCase(hostnameVerifierOption)) {
5929  0 hostnameVerifier = SSLSocketFactory.STRICT_HOSTNAME_VERIFIER;
5930    } else {
5931  0 hostnameVerifier = SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER;
5932    }
5933  145 socketFactory.setHostnameVerifier(hostnameVerifier);
5934   
5935  145 if (APIConstants.HTTPS_PROTOCOL.equals(protocol)) {
5936  143 try {
5937  143 if (APIConstants.SSL_VERIFY_CLIENT_STATUS_REQUIRE.equals(sslValue)) {
5938  0 socketFactory = createSocketFactory();
5939  0 socketFactory.setHostnameVerifier(hostnameVerifier);
5940    }
5941  143 if (port >= 0) {
5942  143 registry.register(new Scheme(APIConstants.HTTPS_PROTOCOL, port, socketFactory));
5943    } else {
5944  0 registry.register(new Scheme(APIConstants.HTTPS_PROTOCOL, 443, socketFactory));
5945    }
5946    } catch (APIManagementException e) {
5947  0 log.error(e);
5948    }
5949  2 } else if (APIConstants.HTTP_PROTOCOL.equals(protocol)) {
5950  2 if (port >= 0) {
5951  2 registry.register(new Scheme(APIConstants.HTTP_PROTOCOL, port, PlainSocketFactory.getSocketFactory()));
5952    } else {
5953  0 registry.register(new Scheme(APIConstants.HTTP_PROTOCOL, 80, PlainSocketFactory.getSocketFactory()));
5954    }
5955    }
5956  145 HttpParams params = new BasicHttpParams();
5957  145 ThreadSafeClientConnManager tcm = new ThreadSafeClientConnManager(registry);
5958  145 return new DefaultHttpClient(tcm, params);
5959   
5960    }
5961   
 
5962  0 toggle private static SSLSocketFactory createSocketFactory() throws APIManagementException {
5963  0 KeyStore keyStore;
5964  0 String keyStorePath = null;
5965  0 String keyStorePassword;
5966  0 try {
5967  0 keyStorePath = CarbonUtils.getServerConfiguration().getFirstProperty("Security.KeyStore.Location");
5968  0 keyStorePassword = CarbonUtils.getServerConfiguration()
5969    .getFirstProperty("Security.KeyStore.Password");
5970  0 keyStore = KeyStore.getInstance("JKS");
5971  0 keyStore.load(new FileInputStream(keyStorePath), keyStorePassword.toCharArray());
5972  0 SSLSocketFactory sslSocketFactory = new SSLSocketFactory(keyStore, keyStorePassword);
5973   
5974  0 return sslSocketFactory;
5975   
5976    } catch (KeyStoreException e) {
5977  0 handleException("Failed to read from Key Store", e);
5978    } catch (CertificateException e) {
5979  0 handleException("Failed to read Certificate", e);
5980    } catch (NoSuchAlgorithmException e) {
5981  0 handleException("Failed to load Key Store from " + keyStorePath, e);
5982    } catch (IOException e) {
5983  0 handleException("Key Store not found in " + keyStorePath, e);
5984    } catch (UnrecoverableKeyException e) {
5985  0 handleException("Failed to load key from" + keyStorePath, e);
5986    } catch (KeyManagementException e) {
5987  0 handleException("Failed to load key from" + keyStorePath, e);
5988    }
5989  0 return null;
5990    }
5991   
5992    /**
5993    * This method will return a relative URL for given registry resource which we can used to retrieve the resource
5994    * from the web UI. For example, URI for a thumbnail icon of a tag can be generated from this method.
5995    *
5996    * @param resourceType Type of the registry resource. Based on this value the way URL is generate can be changed.
5997    * @param tenantDomain tenant domain of the resource
5998    * @param resourcePath path of the resource
5999    * @return relative path of the registry resource from the web context level
6000    */
 
6001  0 toggle public static String getRegistryResourcePathForUI(APIConstants.RegistryResourceTypesForUI resourceType, String
6002    tenantDomain, String resourcePath) {
6003  0 StringBuilder resourcePathBuilder = new StringBuilder();
6004  0 if (APIConstants.RegistryResourceTypesForUI.TAG_THUMBNAIL.equals(resourceType)) {
6005  0 if (tenantDomain != null && !"".equals(tenantDomain)
6006    && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
6007    // The compiler will concatenate the 2 constants. If we use the builder to append the 2 constants, then
6008    // it will happen during the runtime.
6009  0 resourcePathBuilder.append(RegistryConstants.PATH_SEPARATOR + MultitenantConstants
6010    .TENANT_AWARE_URL_PREFIX + RegistryConstants.PATH_SEPARATOR).append(tenantDomain);
6011    }
6012    // The compiler will concatenate the 2 constants. If we use the builder to append the 2 constants, then
6013    // it will happen during the runtime.
6014  0 resourcePathBuilder.append(APIConstants.REGISTRY_RESOURCE_PREFIX + RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH);
6015  0 resourcePathBuilder.append(resourcePath);
6016    }
6017  0 return resourcePathBuilder.toString();
6018    }
6019   
6020    /**
6021    * Gets the class given the class name.
6022    *
6023    * @param className the fully qualified name of the class.
6024    * @return an instance of the class with the given name
6025    * @throws ClassNotFoundException
6026    * @throws IllegalAccessException
6027    * @throws InstantiationException
6028    */
6029   
 
6030  36 toggle public static Class getClassForName(String className) throws ClassNotFoundException, IllegalAccessException,
6031    InstantiationException {
6032  36 return Class.forName(className);
6033    }
6034   
6035    /**
6036    * This method will check the validity of given url.
6037    * otherwise we will mark it as invalid url.
6038    *
6039    * @param url url tobe tested
6040    * @return true if its valid url else fale
6041    */
 
6042  0 toggle public static boolean isValidURL(String url) {
6043   
6044  0 if (url == null) {
6045  0 return false;
6046    }
6047  0 try {
6048  0 URL urlVal = new URL(url);
6049    // If there are no issues, then this is a valid URL. Hence returning true.
6050  0 return true;
6051    } catch (MalformedURLException e) {
6052  0 return false;
6053    }
6054    }
6055   
6056   
6057    /**
6058    * @param tenantDomain Tenant domain to be used to get configurations for REST API scopes
6059    * @return JSON object which contains configuration for REST API scopes
6060    * @throws APIManagementException
6061    */
 
6062  27 toggle public static JSONObject getTenantRESTAPIScopesConfig(String tenantDomain) throws APIManagementException {
6063  27 JSONObject apiTenantConfig = null;
6064  27 JSONObject restAPIConfigJSON = null;
6065  27 try {
6066  27 String content = new APIMRegistryServiceImpl().getConfigRegistryResourceContent(tenantDomain,
6067    APIConstants.API_TENANT_CONF_LOCATION);
6068   
6069  27 if (content != null) {
6070  27 JSONParser parser = new JSONParser();
6071  27 apiTenantConfig = (JSONObject) parser.parse(content);
6072  27 if (apiTenantConfig != null) {
6073  27 Object value = apiTenantConfig.get(APIConstants.REST_API_SCOPES_CONFIG);
6074  27 if (value != null) {
6075  27 restAPIConfigJSON = (JSONObject) value;
6076    } else {
6077  0 throw new APIManagementException("RESTAPIScopes" + " config does not exist for tenant "
6078    + tenantDomain);
6079    }
6080    }
6081    }
6082    } catch (UserStoreException e) {
6083  0 handleException("UserStoreException thrown when getting API tenant config from registry", e);
6084    } catch (RegistryException e) {
6085  0 handleException("RegistryException thrown when getting API tenant config from registry", e);
6086    } catch (ParseException e) {
6087  0 handleException("ParseException thrown when passing API tenant config from registry", e);
6088    }
6089  27 return restAPIConfigJSON;
6090    }
6091   
6092    /**
6093    * @param tenantDomain Tenant domain to be used to get default role configurations
6094    * @return JSON object which contains configuration for default roles
6095    * @throws APIManagementException
6096    */
 
6097  83 toggle public static JSONObject getTenantDefaultRoles(String tenantDomain) throws APIManagementException {
6098  83 JSONObject apiTenantConfig;
6099  83 JSONObject defaultRolesConfigJSON = null;
6100  83 try {
6101  83 String content = new APIMRegistryServiceImpl().getConfigRegistryResourceContent(tenantDomain,
6102    APIConstants.API_TENANT_CONF_LOCATION);
6103   
6104  83 if (content != null) {
6105  83 JSONParser parser = new JSONParser();
6106  83 apiTenantConfig = (JSONObject) parser.parse(content);
6107  83 if (apiTenantConfig != null) {
6108  83 Object value = apiTenantConfig.get(APIConstants.API_TENANT_CONF_DEFAULT_ROLES);
6109  83 if (value != null) {
6110  83 defaultRolesConfigJSON = (JSONObject) value;
6111    } else {
6112    //Config might not exist for migrated environments from previous release
6113  0 if (log.isDebugEnabled()) {
6114  0 log.debug(APIConstants.API_TENANT_CONF_DEFAULT_ROLES + " config does not exist for tenant "
6115    + tenantDomain);
6116    }
6117    }
6118    }
6119    }
6120    } catch (UserStoreException e) {
6121  0 handleException("Error while retrieving user realm for tenant " + tenantDomain, e);
6122    } catch (RegistryException e) {
6123  0 handleException("Error while retrieving tenant configuration file for tenant " + tenantDomain, e);
6124    } catch (ParseException e) {
6125  0 handleException(
6126    "Error while parsing tenant configuration file while retrieving default roles for tenant "
6127    + tenantDomain, e);
6128    }
6129  83 return defaultRolesConfigJSON;
6130    }
6131   
6132    /**
6133    * @param config JSON configuration object with scopes and associated roles
6134    * @return Map of scopes which contains scope names and associated role list
6135    */
 
6136  27 toggle public static Map<String, String> getRESTAPIScopesFromConfig(JSONObject config) {
6137  27 Map<String, String> scopes = new HashMap<String, String>();
6138  27 JSONArray scopesArray = (JSONArray) config.get("Scope");
6139  27 for (Object scopeObj : scopesArray) {
6140  451 JSONObject scope = (JSONObject) scopeObj;
6141  451 String scopeName = scope.get(APIConstants.REST_API_SCOPE_NAME).toString();
6142  451 String scopeRoles = scope.get(APIConstants.REST_API_SCOPE_ROLE).toString();
6143  451 scopes.put(scopeName, scopeRoles);
6144    }
6145  27 return scopes;
6146    }
6147   
6148    /**
6149    * Determines if the scope is specified in the whitelist.
6150    *
6151    * @param scope - The scope key to check
6152    * @return - 'true' if the scope is white listed. 'false' if not.
6153    */
 
6154  12 toggle public static boolean isWhiteListedScope(String scope) {
6155   
6156  12 if (whiteListedScopes == null) {
6157  2 APIManagerConfiguration configuration = ServiceReferenceHolder.getInstance().
6158    getAPIManagerConfigurationService().getAPIManagerConfiguration();
6159   
6160    // Read scope whitelist from Configuration.
6161  2 List<String> whitelist = configuration.getProperty(APIConstants.WHITELISTED_SCOPES);
6162   
6163    // If whitelist is null, default scopes will be put.
6164  2 if (whitelist == null) {
6165  2 whitelist = new ArrayList<String>();
6166  2 whitelist.add(APIConstants.OPEN_ID_SCOPE_NAME);
6167  2 whitelist.add(APIConstants.DEVICE_SCOPE_PATTERN);
6168    }
6169   
6170  2 whiteListedScopes = new HashSet<String>(whitelist);
6171    }
6172   
6173  12 for (String scopeTobeSkipped : whiteListedScopes) {
6174  24 if (scope.matches(scopeTobeSkipped)) {
6175  0 return true;
6176    }
6177    }
6178  12 return false;
6179    }
6180   
 
6181  0 toggle public static String getServerURL() throws APIManagementException {
6182  0 String hostName = ServerConfiguration.getInstance().getFirstProperty(APIConstants.HOST_NAME);
6183   
6184  0 try {
6185  0 if (hostName == null) {
6186  0 hostName = NetworkUtils.getLocalHostname();
6187    }
6188    } catch (SocketException e) {
6189  0 throw new APIManagementException("Error while trying to read hostname.", e);
6190    }
6191   
6192  0 String mgtTransport = CarbonUtils.getManagementTransport();
6193  0 AxisConfiguration axisConfiguration = ServiceReferenceHolder
6194    .getContextService().getServerConfigContext().getAxisConfiguration();
6195  0 int mgtTransportPort = CarbonUtils.getTransportProxyPort(axisConfiguration, mgtTransport);
6196  0 if (mgtTransportPort <= 0) {
6197  0 mgtTransportPort = CarbonUtils.getTransportPort(axisConfiguration, mgtTransport);
6198    }
6199  0 String serverUrl = mgtTransport + "://" + hostName.toLowerCase();
6200    // If it's well known HTTPS port, skip adding port
6201  0 if (mgtTransportPort != APIConstants.DEFAULT_HTTPS_PORT) {
6202  0 serverUrl += ":" + mgtTransportPort;
6203    }
6204    // If ProxyContextPath is defined then append it
6205  0 String proxyContextPath = ServerConfiguration.getInstance().getFirstProperty(APIConstants.PROXY_CONTEXT_PATH);
6206  0 if (proxyContextPath != null && !proxyContextPath.trim().isEmpty()) {
6207  0 if (proxyContextPath.charAt(0) == '/') {
6208  0 serverUrl += proxyContextPath;
6209    } else {
6210  0 serverUrl += "/" + proxyContextPath;
6211    }
6212    }
6213   
6214  0 return serverUrl;
6215    }
6216   
6217    /**
6218    * Extract the provider of the API from name
6219    *
6220    * @param apiVersion - API Name with version
6221    * @param tenantDomain - tenant domain of the API
6222    * @return API publisher name
6223    */
 
6224  0 toggle public static String getAPIProviderFromRESTAPI(String apiVersion, String tenantDomain) {
6225  0 int index = apiVersion.indexOf("--");
6226  0 if (StringUtils.isEmpty(tenantDomain)) {
6227  0 tenantDomain = org.wso2.carbon.utils.multitenancy.MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
6228    }
6229  0 String apiProvider;
6230  0 if (index != -1) {
6231  0 apiProvider = apiVersion.substring(0, index);
6232  0 if (apiProvider.contains(APIConstants.EMAIL_DOMAIN_SEPARATOR_REPLACEMENT)) {
6233  0 apiProvider = apiProvider.replace(APIConstants.EMAIL_DOMAIN_SEPARATOR_REPLACEMENT,
6234    APIConstants.EMAIL_DOMAIN_SEPARATOR);
6235    }
6236  0 if (!apiProvider.endsWith(tenantDomain)) {
6237  0 apiProvider = apiProvider + '@' + tenantDomain;
6238    }
6239  0 return apiProvider;
6240    }
6241  0 return null;
6242    }
6243   
6244    /**
6245    * Used to generate CORS Configuration object from CORS Configuration Json
6246    *
6247    * @param jsonString json representation of CORS configuration
6248    * @return CORSConfiguration Object
6249    */
 
6250  3897 toggle public static CORSConfiguration getCorsConfigurationDtoFromJson(String jsonString) {
6251  3897 return new Gson().fromJson(jsonString, CORSConfiguration.class);
6252   
6253    }
6254   
6255    /**
6256    * Used to generate Json string from CORS Configuration object
6257    *
6258    * @param corsConfiguration CORSConfiguration Object
6259    * @return Json string according to CORSConfiguration Object
6260    */
 
6261  671 toggle public static String getCorsConfigurationJsonFromDto(CORSConfiguration corsConfiguration) {
6262  671 return new Gson().toJson(corsConfiguration);
6263    }
6264   
6265    /**
6266    * Used to get access control allowed headers according to the api-manager.xml
6267    *
6268    * @return access control allowed headers string
6269    */
 
6270  342 toggle public static String getAllowedHeaders() {
6271  342 return ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService().getAPIManagerConfiguration().
6272    getFirstProperty(APIConstants.CORS_CONFIGURATION_ACCESS_CTL_ALLOW_HEADERS);
6273    }
6274   
6275    /**
6276    * Used to get access control allowed methods define in api-manager.xml
6277    *
6278    * @return access control allowed methods string
6279    */
 
6280  342 toggle public static String getAllowedMethods() {
6281  342 return ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService().getAPIManagerConfiguration().
6282    getFirstProperty(APIConstants.CORS_CONFIGURATION_ACCESS_CTL_ALLOW_METHODS);
6283    }
6284   
6285    /**
6286    * Used to get access control allowed credential define in api-manager.xml
6287    *
6288    * @return true if access control allow credential enabled
6289    */
 
6290  323 toggle public static boolean isAllowCredentials() {
6291  323 String allowCredentials =
6292    ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService().getAPIManagerConfiguration().
6293    getFirstProperty(APIConstants.CORS_CONFIGURATION_ACCESS_CTL_ALLOW_CREDENTIALS);
6294  323 return Boolean.parseBoolean(allowCredentials);
6295    }
6296   
6297    /**
6298    * Used to get CORS Configuration enabled from api-manager.xml
6299    *
6300    * @return true if CORS-Configuration is enabled in api-manager.xml
6301    */
 
6302  476 toggle public static boolean isCORSEnabled() {
6303  476 String corsEnabled =
6304    ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService().getAPIManagerConfiguration().
6305    getFirstProperty(APIConstants.CORS_CONFIGURATION_ENABLED);
6306   
6307  476 return Boolean.parseBoolean(corsEnabled);
6308    }
6309   
6310    /**
6311    * Used to get access control allowed origins define in api-manager.xml
6312    *
6313    * @return allow origins list defined in api-manager.xml
6314    */
 
6315  342 toggle public static String getAllowedOrigins() {
6316  342 return ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService().getAPIManagerConfiguration().
6317    getFirstProperty(APIConstants.CORS_CONFIGURATION_ACCESS_CTL_ALLOW_ORIGIN);
6318   
6319    }
6320   
6321    /**
6322    * Used to get CORSConfiguration according to the API artifact
6323    *
6324    * @param artifact registry artifact for the API
6325    * @return CORS Configuration object extract from the artifact
6326    * @throws GovernanceException if attribute couldn't fetch from the artifact.
6327    */
 
6328  3629 toggle public static CORSConfiguration getCorsConfigurationFromArtifact(GovernanceArtifact artifact)
6329    throws GovernanceException {
6330  3629 CORSConfiguration corsConfiguration = APIUtil.getCorsConfigurationDtoFromJson(
6331    artifact.getAttribute(APIConstants.API_OVERVIEW_CORS_CONFIGURATION));
6332  3629 if (corsConfiguration == null) {
6333  4 corsConfiguration = getDefaultCorsConfiguration();
6334    }
6335  3629 return corsConfiguration;
6336    }
6337   
6338    /**
6339    * Used to get Default CORS Configuration object according to configuration define in api-manager.xml
6340    *
6341    * @return CORSConfiguration object accordine to the defined values in api-manager.xml
6342    */
 
6343  19 toggle public static CORSConfiguration getDefaultCorsConfiguration() {
6344  19 List<String> allowHeadersStringSet = Arrays.asList(getAllowedHeaders().split(","));
6345  19 List<String> allowMethodsStringSet = Arrays.asList(getAllowedMethods().split(","));
6346  19 List<String> allowOriginsStringSet = Arrays.asList(getAllowedOrigins().split(","));
6347  19 return new CORSConfiguration(false, allowOriginsStringSet, false, allowHeadersStringSet, allowMethodsStringSet);
6348    }
6349   
6350    /**
6351    * Used to get API name from synapse API Name
6352    *
6353    * @param api_version API name from synapse configuration
6354    * @return api name according to the tenant
6355    */
 
6356  163 toggle public static String getAPINamefromRESTAPI(String api_version) {
6357  163 int index = api_version.indexOf("--");
6358  163 String api;
6359  163 if (index != -1) {
6360  163 api_version = api_version.substring(index + 2);
6361    }
6362  163 api = api_version.split(":")[0];
6363  163 index = api.indexOf("--");
6364  163 if (index != -1) {
6365  0 api = api.substring(index + 2);
6366    }
6367  163 return api;
6368    }
6369   
6370    /**
6371    * @param stakeHolder value "publisher" for publisher value "subscriber" for subscriber value "admin-dashboard" for admin
6372    * Return all alert types.
6373    * @return Hashmap of alert types.
6374    * @throws APIManagementException
6375    */
 
6376  0 toggle public static HashMap<Integer, String> getAllAlertTypeByStakeHolder(String stakeHolder) throws APIManagementException {
6377  0 HashMap<Integer, String> map;
6378  0 map = ApiMgtDAO.getInstance().getAllAlertTypesByStakeHolder(stakeHolder);
6379  0 return map;
6380    }
6381   
6382    /**
6383    * @param userName user name with tenant domain ex: admin@carbon.super
6384    * @param stakeHolder value "p" for publisher value "s" for subscriber value "a" for admin
6385    * @return map of saved values of alert types.
6386    * @throws APIManagementException
6387    */
 
6388  0 toggle public static List<Integer> getSavedAlertTypesIdsByUserNameAndStakeHolder(String userName, String stakeHolder) throws APIManagementException {
6389   
6390  0 List<Integer> list;
6391  0 list = ApiMgtDAO.getInstance().getSavedAlertTypesIdsByUserNameAndStakeHolder(userName, stakeHolder);
6392  0 return list;
6393   
6394    }
6395   
6396    /**
6397    * This util method retrieves saved email list by user and stakeHolder name
6398    *
6399    * @param userName user name with tenant ID.
6400    * @param stakeHolder if its publisher values should "p", if it is store value is "s" if admin dashboard value is "a"
6401    * @return List of eamil list.
6402    * @throws APIManagementException
6403    */
 
6404  0 toggle public static List<String> retrieveSavedEmailList(String userName, String stakeHolder) throws APIManagementException {
6405   
6406  0 List<String> list;
6407  0 list = ApiMgtDAO.getInstance().retrieveSavedEmailList(userName, stakeHolder);
6408   
6409  0 return list;
6410    }
6411   
 
6412  0 toggle private static boolean isDefaultQuotaPolicyContentAware(Policy policy) {
6413  0 if (PolicyConstants.BANDWIDTH_TYPE.equalsIgnoreCase(policy.getDefaultQuotaPolicy().getType())) {
6414  0 return true;
6415    }
6416  0 return false;
6417    }
6418   
 
6419  16 toggle public static void addDefaultSuperTenantAdvancedThrottlePolicies() throws APIManagementException {
6420  16 int tenantId = MultitenantConstants.SUPER_TENANT_ID;
6421  16 ApiMgtDAO apiMgtDAO = ApiMgtDAO.getInstance();
6422   
6423    /* Check if 'Unlimited' policy is available in AM_POLICY_APPLICATION table, to determine whether the default policies are loaded into the database at lease once.
6424    If yes, default policies won't be added to database again.
6425    */
6426  16 if (apiMgtDAO.isPolicyExist(PolicyConstants.POLICY_LEVEL_APP, tenantId, APIConstants.DEFAULT_APP_POLICY_UNLIMITED)) {
6427  16 log.debug("Default Throttling Policies are not written into the database again, as they were added once at initial server startup");
6428  16 return;
6429    }
6430   
6431  0 long[] requestCount = new long[]{50, 20, 10, Integer.MAX_VALUE};
6432    //Adding application level throttle policies
6433  0 String[] appPolicies = new String[]{APIConstants.DEFAULT_APP_POLICY_FIFTY_REQ_PER_MIN, APIConstants.DEFAULT_APP_POLICY_TWENTY_REQ_PER_MIN,
6434    APIConstants.DEFAULT_APP_POLICY_TEN_REQ_PER_MIN, APIConstants.DEFAULT_APP_POLICY_UNLIMITED};
6435  0 String[] appPolicyDecs = new String[]{APIConstants.DEFAULT_APP_POLICY_LARGE_DESC, APIConstants.DEFAULT_APP_POLICY_MEDIUM_DESC,
6436    APIConstants.DEFAULT_APP_POLICY_SMALL_DESC, APIConstants.DEFAULT_APP_POLICY_UNLIMITED_DESC};
6437  0 String policyName;
6438    //Add application level throttle policies
6439  0 for (int i = 0; i < appPolicies.length; i++) {
6440  0 policyName = appPolicies[i];
6441  0 if (!apiMgtDAO.isPolicyExist(PolicyConstants.POLICY_LEVEL_APP, tenantId, policyName)) {
6442  0 ApplicationPolicy applicationPolicy = new ApplicationPolicy(policyName);
6443  0 applicationPolicy.setDisplayName(policyName);
6444  0 applicationPolicy.setDescription(appPolicyDecs[i]);
6445  0 applicationPolicy.setTenantId(tenantId);
6446  0 applicationPolicy.setDeployed(true);
6447  0 QuotaPolicy defaultQuotaPolicy = new QuotaPolicy();
6448  0 RequestCountLimit requestCountLimit = new RequestCountLimit();
6449  0 requestCountLimit.setRequestCount(requestCount[i]);
6450  0 requestCountLimit.setUnitTime(1);
6451  0 requestCountLimit.setTimeUnit(APIConstants.TIME_UNIT_MINUTE);
6452  0 defaultQuotaPolicy.setType(PolicyConstants.REQUEST_COUNT_TYPE);
6453  0 defaultQuotaPolicy.setLimit(requestCountLimit);
6454  0 applicationPolicy.setDefaultQuotaPolicy(defaultQuotaPolicy);
6455  0 apiMgtDAO.addApplicationPolicy(applicationPolicy);
6456    }
6457    }
6458   
6459    //Adding Subscription level policies
6460  0 long[] requestCountSubPolicies = new long[]{5000, 2000, 1000, 500, Integer.MAX_VALUE};
6461  0 String[] subPolicies = new String[]{APIConstants.DEFAULT_SUB_POLICY_GOLD, APIConstants.DEFAULT_SUB_POLICY_SILVER,
6462    APIConstants.DEFAULT_SUB_POLICY_BRONZE, APIConstants.DEFAULT_SUB_POLICY_UNAUTHENTICATED, APIConstants.DEFAULT_SUB_POLICY_UNLIMITED};
6463  0 String[] subPolicyDecs = new String[]{APIConstants.DEFAULT_SUB_POLICY_GOLD_DESC, APIConstants.DEFAULT_SUB_POLICY_SILVER_DESC,
6464    APIConstants.DEFAULT_SUB_POLICY_BRONZE_DESC, APIConstants.DEFAULT_SUB_POLICY_UNAUTHENTICATED_DESC, APIConstants.DEFAULT_SUB_POLICY_UNLIMITED_DESC};
6465  0 for (int i = 0; i < subPolicies.length; i++) {
6466  0 policyName = subPolicies[i];
6467  0 if (!apiMgtDAO.isPolicyExist(PolicyConstants.POLICY_LEVEL_SUB, tenantId, policyName)) {
6468  0 SubscriptionPolicy subscriptionPolicy = new SubscriptionPolicy(policyName);
6469  0 subscriptionPolicy.setDisplayName(policyName);
6470  0 subscriptionPolicy.setDescription(subPolicyDecs[i]);
6471  0 subscriptionPolicy.setTenantId(tenantId);
6472  0 subscriptionPolicy.setDeployed(true);
6473  0 QuotaPolicy defaultQuotaPolicy = new QuotaPolicy();
6474  0 RequestCountLimit requestCountLimit = new RequestCountLimit();
6475  0 requestCountLimit.setRequestCount(requestCountSubPolicies[i]);
6476  0 requestCountLimit.setUnitTime(1);
6477  0 requestCountLimit.setTimeUnit(APIConstants.TIME_UNIT_MINUTE);
6478  0 defaultQuotaPolicy.setType(PolicyConstants.REQUEST_COUNT_TYPE);
6479  0 defaultQuotaPolicy.setLimit(requestCountLimit);
6480  0 subscriptionPolicy.setDefaultQuotaPolicy(defaultQuotaPolicy);
6481  0 subscriptionPolicy.setStopOnQuotaReach(true);
6482  0 subscriptionPolicy.setBillingPlan(APIConstants.BILLING_PLAN_FREE);
6483  0 apiMgtDAO.addSubscriptionPolicy(subscriptionPolicy);
6484    }
6485    }
6486   
6487    //Adding Resource level policies
6488  0 String[] apiPolicies = new String[]{APIConstants.DEFAULT_API_POLICY_FIFTY_THOUSAND_REQ_PER_MIN, APIConstants.DEFAULT_API_POLICY_TWENTY_THOUSAND_REQ_PER_MIN,
6489    APIConstants.DEFAULT_API_POLICY_TEN_THOUSAND_REQ_PER_MIN, APIConstants.DEFAULT_API_POLICY_UNLIMITED};
6490  0 String[] apiPolicyDecs = new String[]{APIConstants.DEFAULT_API_POLICY_ULTIMATE_DESC, APIConstants.DEFAULT_API_POLICY_PLUS_DESC,
6491    APIConstants.DEFAULT_API_POLICY_BASIC_DESC, APIConstants.DEFAULT_API_POLICY_UNLIMITED_DESC};
6492  0 long[] requestCountApiPolicies = new long[]{50000, 20000, 10000, Integer.MAX_VALUE};
6493  0 for (int i = 0; i < apiPolicies.length; i++) {
6494  0 policyName = apiPolicies[i];
6495  0 if (!apiMgtDAO.isPolicyExist(PolicyConstants.POLICY_LEVEL_API, tenantId, policyName)) {
6496  0 APIPolicy apiPolicy = new APIPolicy(policyName);
6497  0 apiPolicy.setDisplayName(policyName);
6498  0 apiPolicy.setDescription(apiPolicyDecs[i]);
6499  0 apiPolicy.setTenantId(tenantId);
6500  0 apiPolicy.setUserLevel(APIConstants.API_POLICY_API_LEVEL);
6501  0 apiPolicy.setDeployed(true);
6502  0 QuotaPolicy defaultQuotaPolicy = new QuotaPolicy();
6503  0 RequestCountLimit requestCountLimit = new RequestCountLimit();
6504  0 requestCountLimit.setRequestCount(requestCountApiPolicies[i]);
6505  0 requestCountLimit.setUnitTime(1);
6506  0 requestCountLimit.setTimeUnit(APIConstants.TIME_UNIT_MINUTE);
6507  0 defaultQuotaPolicy.setType(PolicyConstants.REQUEST_COUNT_TYPE);
6508  0 defaultQuotaPolicy.setLimit(requestCountLimit);
6509  0 apiPolicy.setDefaultQuotaPolicy(defaultQuotaPolicy);
6510  0 apiMgtDAO.addAPIPolicy(apiPolicy);
6511    }
6512    }
6513    }
6514   
 
6515  17 toggle public static void addDefaultTenantAdvancedThrottlePolicies(String tenantDomain, int tenantId) throws APIManagementException {
6516  17 ApiMgtDAO apiMgtDAO = ApiMgtDAO.getInstance();
6517   
6518    /* Check if 'Unlimited' policy is available in AM_POLICY_APPLICATION table, to determine whether the default policies are written into the database at lease once.
6519    If yes, default policies won't be added to database again.
6520    */
6521  17 if (apiMgtDAO.isPolicyExist(PolicyConstants.POLICY_LEVEL_APP, tenantId, APIConstants.DEFAULT_APP_POLICY_UNLIMITED)) {
6522  12 log.debug("Default Throttling Policies are not written into the database again, as they were added once, at initial tenant loading");
6523  12 return;
6524    }
6525   
6526  5 ThrottlePolicyDeploymentManager deploymentManager = ThrottlePolicyDeploymentManager.getInstance();
6527  5 ThrottlePolicyTemplateBuilder policyBuilder = new ThrottlePolicyTemplateBuilder();
6528  5 Map<String, Long> defualtLimits = ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService().getAPIManagerConfiguration()
6529    .getThrottleProperties().getDefaultThrottleTierLimits();
6530  5 long tenPerMinTier = defualtLimits.containsKey(APIConstants.DEFAULT_APP_POLICY_TEN_REQ_PER_MIN) ?
6531    defualtLimits.get(APIConstants.DEFAULT_APP_POLICY_TEN_REQ_PER_MIN) : 10;
6532  5 long twentyPerMinTier = defualtLimits.containsKey(APIConstants.DEFAULT_APP_POLICY_TWENTY_REQ_PER_MIN) ?
6533    defualtLimits.get(APIConstants.DEFAULT_APP_POLICY_TWENTY_REQ_PER_MIN) : 20;
6534  5 long fiftyPerMinTier = defualtLimits.containsKey(APIConstants.DEFAULT_APP_POLICY_FIFTY_REQ_PER_MIN) ?
6535    defualtLimits.get(APIConstants.DEFAULT_APP_POLICY_FIFTY_REQ_PER_MIN) : 50;
6536  5 long[] requestCount = new long[]{fiftyPerMinTier, twentyPerMinTier, tenPerMinTier, Integer.MAX_VALUE};
6537    //Adding application level throttle policies
6538  5 String[] appPolicies = new String[]{APIConstants.DEFAULT_APP_POLICY_FIFTY_REQ_PER_MIN, APIConstants.DEFAULT_APP_POLICY_TWENTY_REQ_PER_MIN,
6539    APIConstants.DEFAULT_APP_POLICY_TEN_REQ_PER_MIN, APIConstants.DEFAULT_APP_POLICY_UNLIMITED};
6540  5 String[] appPolicyDecs = new String[]{APIConstants.DEFAULT_APP_POLICY_LARGE_DESC, APIConstants.DEFAULT_APP_POLICY_MEDIUM_DESC,
6541    APIConstants.DEFAULT_APP_POLICY_SMALL_DESC, APIConstants.DEFAULT_APP_POLICY_UNLIMITED_DESC};
6542  5 String policyName;
6543    //Add application level throttle policies
6544  25 for (int i = 0; i < appPolicies.length; i++) {
6545  20 policyName = appPolicies[i];
6546  20 boolean needDeployment = false;
6547  20 ApplicationPolicy applicationPolicy = new ApplicationPolicy(policyName);
6548  20 applicationPolicy.setDisplayName(policyName);
6549  20 applicationPolicy.setDescription(appPolicyDecs[i]);
6550  20 applicationPolicy.setTenantId(tenantId);
6551  20 applicationPolicy.setDeployed(false);
6552  20 applicationPolicy.setTenantDomain(tenantDomain);
6553  20 QuotaPolicy defaultQuotaPolicy = new QuotaPolicy();
6554  20 RequestCountLimit requestCountLimit = new RequestCountLimit();
6555  20 requestCountLimit.setRequestCount(requestCount[i]);
6556  20 requestCountLimit.setUnitTime(1);
6557  20 requestCountLimit.setTimeUnit(APIConstants.TIME_UNIT_MINUTE);
6558  20 defaultQuotaPolicy.setType(PolicyConstants.REQUEST_COUNT_TYPE);
6559  20 defaultQuotaPolicy.setLimit(requestCountLimit);
6560  20 applicationPolicy.setDefaultQuotaPolicy(defaultQuotaPolicy);
6561   
6562  20 if (!apiMgtDAO.isPolicyExist(PolicyConstants.POLICY_LEVEL_APP, tenantId, policyName)) {
6563  20 apiMgtDAO.addApplicationPolicy(applicationPolicy);
6564  20 needDeployment = true;
6565    }
6566   
6567  20 if (!apiMgtDAO.isPolicyDeployed(PolicyConstants.POLICY_LEVEL_APP, tenantId, policyName)) {
6568  20 needDeployment = true;
6569    }
6570   
6571  20 if (needDeployment) {
6572  20 String policyString;
6573  20 try {
6574  20 policyString = policyBuilder.getThrottlePolicyForAppLevel(applicationPolicy);
6575  20 String policyFile = applicationPolicy.getTenantDomain() + "_" + PolicyConstants.POLICY_LEVEL_APP +
6576    "_" + applicationPolicy.getPolicyName();
6577  20 if (!APIConstants.DEFAULT_APP_POLICY_UNLIMITED.equalsIgnoreCase(policyName)) {
6578  15 deploymentManager.deployPolicyToGlobalCEP(policyString);
6579    }
6580  20 apiMgtDAO.setPolicyDeploymentStatus(PolicyConstants.POLICY_LEVEL_APP, applicationPolicy.getPolicyName(),
6581    applicationPolicy.getTenantId(), true);
6582    } catch (APITemplateException e) {
6583  0 throw new APIManagementException("Error while adding default subscription policy" + applicationPolicy.getPolicyName(), e);
6584    }
6585    }
6586    }
6587   
6588  5 long bronzeTierLimit = defualtLimits.containsKey(APIConstants.DEFAULT_SUB_POLICY_BRONZE) ?
6589    defualtLimits.get(APIConstants.DEFAULT_SUB_POLICY_BRONZE) : 1000;
6590  5 long silverTierLimit = defualtLimits.containsKey(APIConstants.DEFAULT_SUB_POLICY_SILVER) ?
6591    defualtLimits.get(APIConstants.DEFAULT_SUB_POLICY_SILVER) : 2000;
6592  5 long goldTierLimit = defualtLimits.containsKey(APIConstants.DEFAULT_SUB_POLICY_GOLD) ?
6593    defualtLimits.get(APIConstants.DEFAULT_SUB_POLICY_GOLD) : 5000;
6594  5 long unauthenticatedTierLimit = defualtLimits.containsKey(APIConstants.DEFAULT_APP_POLICY_FIFTY_REQ_PER_MIN) ?
6595    defualtLimits.get(APIConstants.DEFAULT_SUB_POLICY_UNAUTHENTICATED) : 500;
6596    //Adding Subscription level policies
6597  5 long[] requestCountSubPolicies = new long[]{goldTierLimit, silverTierLimit, bronzeTierLimit, unauthenticatedTierLimit, Integer.MAX_VALUE};
6598  5 String[] subPolicies = new String[]{APIConstants.DEFAULT_SUB_POLICY_GOLD, APIConstants.DEFAULT_SUB_POLICY_SILVER,
6599    APIConstants.DEFAULT_SUB_POLICY_BRONZE, APIConstants.DEFAULT_SUB_POLICY_UNAUTHENTICATED, APIConstants.DEFAULT_SUB_POLICY_UNLIMITED};
6600  5 String[] subPolicyDecs = new String[]{APIConstants.DEFAULT_SUB_POLICY_GOLD_DESC, APIConstants.DEFAULT_SUB_POLICY_SILVER_DESC,
6601    APIConstants.DEFAULT_SUB_POLICY_BRONZE_DESC, APIConstants.DEFAULT_SUB_POLICY_UNAUTHENTICATED_DESC, APIConstants.DEFAULT_SUB_POLICY_UNLIMITED_DESC};
6602  30 for (int i = 0; i < subPolicies.length; i++) {
6603  25 policyName = subPolicies[i];
6604  25 boolean needDeployment = false;
6605  25 SubscriptionPolicy subscriptionPolicy = new SubscriptionPolicy(policyName);
6606  25 subscriptionPolicy.setDisplayName(policyName);
6607  25 subscriptionPolicy.setDescription(subPolicyDecs[i]);
6608  25 subscriptionPolicy.setTenantId(tenantId);
6609  25 subscriptionPolicy.setDeployed(false);
6610  25 subscriptionPolicy.setTenantDomain(tenantDomain);
6611  25 QuotaPolicy defaultQuotaPolicy = new QuotaPolicy();
6612  25 RequestCountLimit requestCountLimit = new RequestCountLimit();
6613  25 requestCountLimit.setRequestCount(requestCountSubPolicies[i]);
6614  25 requestCountLimit.setUnitTime(1);
6615  25 requestCountLimit.setTimeUnit(APIConstants.TIME_UNIT_MINUTE);
6616  25 defaultQuotaPolicy.setType(PolicyConstants.REQUEST_COUNT_TYPE);
6617  25 defaultQuotaPolicy.setLimit(requestCountLimit);
6618  25 subscriptionPolicy.setDefaultQuotaPolicy(defaultQuotaPolicy);
6619  25 subscriptionPolicy.setStopOnQuotaReach(true);
6620  25 subscriptionPolicy.setBillingPlan(APIConstants.BILLING_PLAN_FREE);
6621   
6622  25 if (!apiMgtDAO.isPolicyExist(PolicyConstants.POLICY_LEVEL_SUB, tenantId, policyName)) {
6623  25 apiMgtDAO.addSubscriptionPolicy(subscriptionPolicy);
6624  25 needDeployment = true;
6625    }
6626   
6627  25 if (!apiMgtDAO.isPolicyDeployed(PolicyConstants.POLICY_LEVEL_SUB, tenantId, policyName)) {
6628  25 needDeployment = true;
6629    }
6630   
6631  25 if (needDeployment) {
6632  25 String policyString;
6633  25 try {
6634  25 policyString = policyBuilder.getThrottlePolicyForSubscriptionLevel(subscriptionPolicy);
6635  25 String policyFile = subscriptionPolicy.getTenantDomain() + "_" + PolicyConstants.POLICY_LEVEL_SUB +
6636    "_" + subscriptionPolicy.getPolicyName();
6637  25 if (!APIConstants.DEFAULT_SUB_POLICY_UNLIMITED.equalsIgnoreCase(policyName)) {
6638  20 deploymentManager.deployPolicyToGlobalCEP(policyString);
6639    }
6640  25 apiMgtDAO.setPolicyDeploymentStatus(PolicyConstants.POLICY_LEVEL_SUB, subscriptionPolicy.getPolicyName(),
6641    subscriptionPolicy.getTenantId(), true);
6642    } catch (APITemplateException e) {
6643  0 throw new APIManagementException("Error while adding default application policy " + subscriptionPolicy.getPolicyName(), e);
6644    }
6645    }
6646    }
6647   
6648  5 long tenThousandPerMinTier = defualtLimits.containsKey(APIConstants.DEFAULT_API_POLICY_TEN_THOUSAND_REQ_PER_MIN) ?
6649    defualtLimits.get(APIConstants.DEFAULT_API_POLICY_TEN_THOUSAND_REQ_PER_MIN) : 10000;
6650  5 long twentyThousandPerMinTier = defualtLimits.containsKey(APIConstants.DEFAULT_API_POLICY_TWENTY_THOUSAND_REQ_PER_MIN) ?
6651    defualtLimits.get(APIConstants.DEFAULT_API_POLICY_TWENTY_THOUSAND_REQ_PER_MIN) : 20000;
6652  5 long fiftyThousandPerMinTier = defualtLimits.containsKey(APIConstants.DEFAULT_API_POLICY_FIFTY_THOUSAND_REQ_PER_MIN) ?
6653    defualtLimits.get(APIConstants.DEFAULT_API_POLICY_FIFTY_THOUSAND_REQ_PER_MIN) : 50000;
6654  5 long[] requestCountAPIPolicies = new long[]{fiftyThousandPerMinTier, twentyThousandPerMinTier, tenThousandPerMinTier, Integer.MAX_VALUE};
6655   
6656    //Adding Resource level policies
6657  5 String[] apiPolicies = new String[]{APIConstants.DEFAULT_API_POLICY_FIFTY_THOUSAND_REQ_PER_MIN, APIConstants.DEFAULT_API_POLICY_TWENTY_THOUSAND_REQ_PER_MIN,
6658    APIConstants.DEFAULT_API_POLICY_TEN_THOUSAND_REQ_PER_MIN, APIConstants.DEFAULT_API_POLICY_UNLIMITED};
6659  5 String[] apiPolicyDecs = new String[]{APIConstants.DEFAULT_API_POLICY_ULTIMATE_DESC, APIConstants.DEFAULT_API_POLICY_PLUS_DESC,
6660    APIConstants.DEFAULT_API_POLICY_BASIC_DESC, APIConstants.DEFAULT_API_POLICY_UNLIMITED_DESC};
6661  25 for (int i = 0; i < apiPolicies.length; i++) {
6662  20 boolean needDeployment = false;
6663  20 policyName = apiPolicies[i];
6664  20 APIPolicy apiPolicy = new APIPolicy(policyName);
6665  20 apiPolicy.setDisplayName(policyName);
6666  20 apiPolicy.setDescription(apiPolicyDecs[i]);
6667  20 apiPolicy.setTenantId(tenantId);
6668  20 apiPolicy.setUserLevel(APIConstants.API_POLICY_API_LEVEL);
6669  20 apiPolicy.setDeployed(false);
6670  20 apiPolicy.setTenantDomain(tenantDomain);
6671  20 QuotaPolicy defaultQuotaPolicy = new QuotaPolicy();
6672  20 RequestCountLimit requestCountLimit = new RequestCountLimit();
6673  20 requestCountLimit.setRequestCount(requestCountAPIPolicies[i]);
6674  20 requestCountLimit.setUnitTime(1);
6675  20 requestCountLimit.setTimeUnit(APIConstants.TIME_UNIT_MINUTE);
6676  20 defaultQuotaPolicy.setType(PolicyConstants.REQUEST_COUNT_TYPE);
6677  20 defaultQuotaPolicy.setLimit(requestCountLimit);
6678  20 apiPolicy.setDefaultQuotaPolicy(defaultQuotaPolicy);
6679   
6680  20 if (!apiMgtDAO.isPolicyExist(PolicyConstants.POLICY_LEVEL_API, tenantId, policyName)) {
6681  20 apiMgtDAO.addAPIPolicy(apiPolicy);
6682    }
6683   
6684  20 if (!apiMgtDAO.isPolicyDeployed(PolicyConstants.POLICY_LEVEL_API, tenantId, policyName)) {
6685  20 needDeployment = true;
6686    }
6687   
6688  20 if (needDeployment) {
6689  20 String policyString;
6690  20 try {
6691  20 policyString = policyBuilder.getThrottlePolicyForAPILevelDefault(apiPolicy);
6692  20 String policyFile = apiPolicy.getTenantDomain() + "_" + PolicyConstants.POLICY_LEVEL_API +
6693    "_" + apiPolicy.getPolicyName() + "_default";
6694  20 if (!APIConstants.DEFAULT_API_POLICY_UNLIMITED.equalsIgnoreCase(policyName)) {
6695  15 deploymentManager.deployPolicyToGlobalCEP(policyString);
6696    }
6697  20 apiMgtDAO.setPolicyDeploymentStatus(PolicyConstants.POLICY_LEVEL_API, apiPolicy.getPolicyName(),
6698    apiPolicy.getTenantId(), true);
6699    } catch (APITemplateException e) {
6700  0 throw new APIManagementException("Error while adding default api policy " + apiPolicy.getPolicyName(), e);
6701    }
6702    }
6703    }
6704    }
6705   
6706    /**
6707    * Used to get advence throttling is enable
6708    *
6709    * @return condition of advance throttling
6710    */
 
6711  8407 toggle public static boolean isAdvanceThrottlingEnabled() {
6712  8407 return ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService().getAPIManagerConfiguration()
6713    .getThrottleProperties().isEnabled();
6714    }
6715   
6716    /**
6717    * Used to get unlimited throttling tier is enable
6718    *
6719    * @return condition of enable unlimited tier
6720    */
 
6721  3282 toggle public static boolean isEnabledUnlimitedTier() {
6722  3282 ThrottleProperties throttleProperties = ServiceReferenceHolder.getInstance()
6723    .getAPIManagerConfigurationService().getAPIManagerConfiguration()
6724    .getThrottleProperties();
6725  3282 if (throttleProperties.isEnabled()) {
6726  3097 return throttleProperties.isEnableUnlimitedTier();
6727    } else {
6728  185 APIManagerConfiguration config = ServiceReferenceHolder.getInstance().
6729    getAPIManagerConfigurationService().getAPIManagerConfiguration();
6730  185 return JavaUtils.isTrueExplicitly(config.getFirstProperty(APIConstants.ENABLE_UNLIMITED_TIER));
6731    }
6732    }
6733   
6734    /**
6735    * Used to get subscription Spike arrest Enable
6736    *
6737    * @return condition of Subscription Spike arrest configuration
6738    */
 
6739  0 toggle public static boolean isEnabledSubscriptionSpikeArrest() {
6740  0 ThrottleProperties throttleProperties = ServiceReferenceHolder.getInstance()
6741    .getAPIManagerConfigurationService().getAPIManagerConfiguration()
6742    .getThrottleProperties();
6743  0 return throttleProperties.isEnabledSubscriptionLevelSpikeArrest();
6744    }
6745   
6746    /**
6747    * This method is used to get the labels in a given tenant space
6748    *
6749    * @param tenantDomain tenant domain name
6750    * @return micro gateway labels in a given tenant space
6751    * @throws APIManagementException if failed to fetch micro gateway labels
6752    */
 
6753  824 toggle public static List<Label> getAllLabels(String tenantDomain) throws APIManagementException {
6754  824 ApiMgtDAO apiMgtDAO = ApiMgtDAO.getInstance();
6755  824 return apiMgtDAO.getAllLabels(tenantDomain);
6756    }
6757   
 
6758  3065 toggle public static Map<String, Tier> getTiersFromPolicies(String policyLevel, int tenantId) throws APIManagementException {
6759  3065 Map<String, Tier> tierMap = new HashMap<String, Tier>();
6760  3065 ApiMgtDAO apiMgtDAO = ApiMgtDAO.getInstance();
6761  3065 Policy[] policies;
6762  3065 if (PolicyConstants.POLICY_LEVEL_SUB.equalsIgnoreCase(policyLevel)) {
6763  2928 policies = apiMgtDAO.getSubscriptionPolicies(tenantId);
6764  137 } else if (PolicyConstants.POLICY_LEVEL_API.equalsIgnoreCase(policyLevel)) {
6765  0 policies = apiMgtDAO.getAPIPolicies(tenantId);
6766  137 } else if (PolicyConstants.POLICY_LEVEL_APP.equalsIgnoreCase(policyLevel)) {
6767  137 policies = apiMgtDAO.getApplicationPolicies(tenantId);
6768    } else {
6769  0 throw new APIManagementException("No such a policy type : " + policyLevel);
6770    }
6771   
6772  3065 for (Policy policy : policies) {
6773  15182 if (!APIConstants.UNLIMITED_TIER.equalsIgnoreCase(policy.getPolicyName())) {
6774  12119 Tier tier = new Tier(policy.getPolicyName());
6775  12119 tier.setDescription(policy.getDescription());
6776  12119 tier.setDisplayName(policy.getDisplayName());
6777  12119 Limit limit = policy.getDefaultQuotaPolicy().getLimit();
6778  12119 tier.setTimeUnit(limit.getTimeUnit());
6779  12119 tier.setUnitTime(limit.getUnitTime());
6780   
6781    //If the policy is a subscription policy
6782  12119 if (policy instanceof SubscriptionPolicy) {
6783  11708 SubscriptionPolicy subscriptionPolicy = (SubscriptionPolicy) policy;
6784  11708 setBillingPlanAndCustomAttributesToTier(subscriptionPolicy, tier);
6785    }
6786   
6787  12119 if (limit instanceof RequestCountLimit) {
6788   
6789  12119 RequestCountLimit countLimit = (RequestCountLimit) limit;
6790  12119 tier.setRequestsPerMin(countLimit.getRequestCount());
6791  12119 tier.setRequestCount(countLimit.getRequestCount());
6792    } else {
6793  0 BandwidthLimit bandwidthLimit = (BandwidthLimit) limit;
6794  0 tier.setRequestsPerMin(bandwidthLimit.getDataAmount());
6795  0 tier.setRequestCount(bandwidthLimit.getDataAmount());
6796    }
6797  12119 if (PolicyConstants.POLICY_LEVEL_SUB.equalsIgnoreCase(policyLevel)) {
6798  11708 tier.setTierPlan(((SubscriptionPolicy) policy).getBillingPlan());
6799    }
6800  12119 tierMap.put(policy.getPolicyName(), tier);
6801    } else {
6802  3063 if (APIUtil.isEnabledUnlimitedTier()) {
6803  3063 Tier tier = new Tier(policy.getPolicyName());
6804  3063 tier.setDescription(policy.getDescription());
6805  3063 tier.setDisplayName(policy.getDisplayName());
6806  3063 tier.setRequestsPerMin(Integer.MAX_VALUE);
6807  3063 tier.setRequestCount(Integer.MAX_VALUE);
6808  3063 if (isUnlimitedTierPaid(getTenantDomainFromTenantId(tenantId))) {
6809  0 tier.setTierPlan(APIConstants.COMMERCIAL_TIER_PLAN);
6810    } else {
6811  3063 tier.setTierPlan(APIConstants.BILLING_PLAN_FREE);
6812    }
6813   
6814  3063 tierMap.put(policy.getPolicyName(), tier);
6815    }
6816    }
6817    }
6818   
6819  3065 if (PolicyConstants.POLICY_LEVEL_SUB.equalsIgnoreCase(policyLevel)) {
6820  2928 tierMap.remove(APIConstants.UNAUTHENTICATED_TIER);
6821    }
6822  3065 return tierMap;
6823    }
6824   
6825    /**
6826    * Extract custom attributes and billing plan from subscription policy and set to tier.
6827    *
6828    * @param subscriptionPolicy - The SubscriptionPolicy object to extract details from
6829    * @param tier - The Tier to set information into
6830    */
 
6831  11708 toggle public static void setBillingPlanAndCustomAttributesToTier(SubscriptionPolicy subscriptionPolicy, Tier tier) {
6832   
6833    //set the billing plan.
6834  11708 tier.setTierPlan(subscriptionPolicy.getBillingPlan());
6835   
6836    //If the tier has custom attributes
6837  11708 if (subscriptionPolicy.getCustomAttributes() != null &&
6838    subscriptionPolicy.getCustomAttributes().length > 0) {
6839   
6840  0 Map<String, Object> tierAttributes = new HashMap<String, Object>();
6841  0 try {
6842  0 String customAttr = new String(subscriptionPolicy.getCustomAttributes(), "UTF-8");
6843  0 JSONParser parser = new JSONParser();
6844  0 JSONArray jsonArr = (JSONArray) parser.parse(customAttr);
6845  0 Iterator jsonArrIterator = jsonArr.iterator();
6846  0 while (jsonArrIterator.hasNext()) {
6847  0 JSONObject json = (JSONObject) jsonArrIterator.next();
6848  0 tierAttributes.put(String.valueOf(json.get("name")), json.get("value"));
6849    }
6850  0 tier.setTierAttributes(tierAttributes);
6851    } catch (ParseException e) {
6852  0 log.error("Unable to convert String to Json", e);
6853  0 tier.setTierAttributes(null);
6854    } catch (UnsupportedEncodingException e) {
6855  0 log.error("Custom attribute byte array does not use UTF-8 character set", e);
6856  0 tier.setTierAttributes(null);
6857    }
6858    }
6859    }
6860   
 
6861  2899 toggle public static Set<Tier> getAvailableTiers(Map<String, Tier> definedTiers, String tiers, String apiName) {
6862  2899 Set<Tier> availableTier = new HashSet<Tier>();
6863  2899 if (tiers != null && !"".equals(tiers)) {
6864  2879 String[] tierNames = tiers.split("\\|\\|");
6865  2879 for (String tierName : tierNames) {
6866  3846 Tier definedTier = definedTiers.get(tierName);
6867  3846 if (definedTier != null) {
6868  3846 availableTier.add(definedTier);
6869    } else {
6870  0 log.warn("Unknown tier: " + tierName + " found on API: " + apiName);
6871    }
6872    }
6873    }
6874  2899 return availableTier;
6875    }
6876   
 
6877  0 toggle public static byte[] toByteArray(InputStream is) throws IOException {
6878  0 return IOUtils.toByteArray(is);
6879    }
6880   
 
6881  198 toggle public static long ipToLong(String ipAddress) {
6882  198 long result = 0;
6883  198 String[] ipAddressInArray = ipAddress.split("\\.");
6884  990 for (int i = 3; i >= 0; i--) {
6885  792 long ip = Long.parseLong(ipAddressInArray[3 - i]);
6886    //left shifting 24,16,8,0 and bitwise OR
6887    //1. 192 << 24
6888    //1. 168 << 16
6889    //1. 1 << 8
6890    //1. 2 << 0
6891  792 result |= ip << (i * 8);
6892   
6893    }
6894  198 return result;
6895    }
6896   
 
6897  0 toggle public String getFullLifeCycleData(Registry registry) throws XMLStreamException, RegistryException {
6898  0 return CommonUtil.getLifecycleConfiguration(APIConstants.API_LIFE_CYCLE, registry);
6899   
6900    }
6901   
6902    /**
6903    * Composes OR based search criteria from provided array of values
6904    *
6905    * @param values
6906    * @return
6907    */
 
6908  43 toggle public static String getORBasedSearchCriteria(String[] values) {
6909  43 String criteria = "(";
6910  43 if (values != null) {
6911  120 for (int i = 0; i < values.length; i++) {
6912  77 criteria = criteria + values[i];
6913  77 if (i != values.length - 1) {
6914  34 criteria = criteria + " OR ";
6915    } else {
6916  43 criteria = criteria + ")";
6917    }
6918    }
6919  43 return criteria;
6920    }
6921  0 return null;
6922    }
6923   
6924    /**
6925    * Generates solr compatible search criteria synatax from user entered query criteria.
6926    * Ex: From version:1.0.0, this returns version=*1.0.0*
6927    *
6928    * @param criteria
6929    * @return solar compatible criteria
6930    * @throws APIManagementException
6931    */
 
6932  38 toggle public static String getSingleSearchCriteria(String criteria) throws APIManagementException {
6933  38 criteria = criteria.trim();
6934  38 String searchValue = criteria;
6935  38 String searchKey = APIConstants.NAME_TYPE_PREFIX;
6936   
6937  38 if (criteria.contains(":")) {
6938  6 if (criteria.split(":").length > 1) {
6939  6 String[] splitValues = criteria.split(":");
6940  6 searchKey = splitValues[0].trim();
6941  6 searchValue = splitValues[1];
6942    //if search key is 'tag' instead of 'tags', allow it as well since rest api document says query
6943    // param to use for tag search is 'tag'
6944   
6945  6 if (APIConstants.TAG_SEARCH_TYPE_PREFIX3.equals(searchKey)) {
6946  0 searchKey = APIConstants.TAG_SEARCH_TYPE_PREFIX;
6947  0 searchValue = searchValue.replace(" ", "\\ ");
6948    }
6949   
6950  6 if (!APIConstants.DOCUMENTATION_SEARCH_TYPE_PREFIX.equalsIgnoreCase(searchKey) &&
6951    !APIConstants.TAG_SEARCH_TYPE_PREFIX.equalsIgnoreCase(searchKey)) {
6952  0 if (!(searchValue.endsWith("\"") && searchValue.startsWith("\""))) {
6953  0 if (!searchValue.endsWith("*")) {
6954  0 searchValue = searchValue + "*";
6955    }
6956  0 if (!searchValue.startsWith("*")) {
6957  0 searchValue = "*" + searchValue;
6958    }
6959    }
6960    }
6961   
6962    } else {
6963  0 throw new APIManagementException("Search term is missing. Try again with valid search query.");
6964    }
6965    } else {
6966  32 if (!(searchValue.endsWith("\"") && searchValue.startsWith("\""))) {
6967  32 if (!searchValue.endsWith("*")) {
6968  32 searchValue = searchValue + "*";
6969    }
6970  32 if (!searchValue.startsWith("*")) {
6971  1 searchValue = "*" + searchValue;
6972    }
6973    }
6974    }
6975  38 if (APIConstants.API_PROVIDER.equalsIgnoreCase(searchKey)) {
6976  0 searchValue = searchValue.replaceAll("@", "-AT-");
6977    }
6978  38 return searchKey + "=" + searchValue;
6979    }
6980   
6981    /**
6982    * return whether store forum feature is enabled
6983    *
6984    * @return true or false indicating enable or not
6985    */
 
6986  50 toggle public static boolean isStoreForumEnabled() {
6987  50 APIManagerConfiguration config = ServiceReferenceHolder.getInstance().
6988    getAPIManagerConfigurationService().getAPIManagerConfiguration();
6989  50 String forumEnabled = config.getFirstProperty(APIConstants.API_STORE_FORUM_ENABLED);
6990  50 if (forumEnabled == null) {
6991  50 return true;
6992    }
6993  0 return Boolean.parseBoolean(forumEnabled);
6994    }
6995   
6996    /**
6997    * Returns a secured DocumentBuilderFactory instance
6998    *
6999    * @return DocumentBuilderFactory
7000    */
 
7001  48 toggle public static DocumentBuilderFactory getSecuredDocumentBuilder() {
7002   
7003  48 org.apache.xerces.impl.Constants Constants = null;
7004  48 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
7005  48 dbf.setNamespaceAware(true);
7006  48 dbf.setXIncludeAware(false);
7007  48 dbf.setExpandEntityReferences(false);
7008  48 try {
7009  48 dbf.setFeature(Constants.SAX_FEATURE_PREFIX + Constants.EXTERNAL_GENERAL_ENTITIES_FEATURE, false);
7010  48 dbf.setFeature(Constants.SAX_FEATURE_PREFIX + Constants.EXTERNAL_PARAMETER_ENTITIES_FEATURE, false);
7011  48 dbf.setFeature(Constants.XERCES_FEATURE_PREFIX + Constants.LOAD_EXTERNAL_DTD_FEATURE, false);
7012    } catch (ParserConfigurationException e) {
7013  0 log.error(
7014    "Failed to load XML Processor Feature " + Constants.EXTERNAL_GENERAL_ENTITIES_FEATURE + " or " +
7015    Constants.EXTERNAL_PARAMETER_ENTITIES_FEATURE + " or " + Constants.LOAD_EXTERNAL_DTD_FEATURE);
7016    }
7017   
7018  48 SecurityManager securityManager = new SecurityManager();
7019  48 securityManager.setEntityExpansionLimit(ENTITY_EXPANSION_LIMIT);
7020  48 dbf.setAttribute(Constants.XERCES_PROPERTY_PREFIX + Constants.SECURITY_MANAGER_PROPERTY, securityManager);
7021   
7022  48 return dbf;
7023    }
7024   
7025    /**
7026    * Logs an audit message on actions performed on entities (APIs, Applications, etc). The log is printed in the
7027    * following JSON format
7028    * {
7029    * "typ": "API",
7030    * "action": "update",
7031    * "performedBy": "admin@carbon.super",
7032    * "info": {
7033    * "name": "Twitter",
7034    * "context": "/twitter",
7035    * "version": "1.0.0",
7036    * "provider": "nuwan"
7037    * }
7038    * }
7039    *
7040    * @param entityType - The entity type. Ex: API, Application
7041    * @param entityInfo - The details of the entity. Ex: API Name, Context
7042    * @param action - The type of action performed. Ex: Create, Update
7043    * @param performedBy - The user who performs the action.
7044    */
 
7045  1143 toggle public static void logAuditMessage(String entityType, String entityInfo, String action, String performedBy) {
7046  1143 JSONObject jsonObject = new JSONObject();
7047  1143 jsonObject.put("typ", entityType);
7048  1143 jsonObject.put("action", action);
7049  1143 jsonObject.put("performedBy", performedBy);
7050  1143 jsonObject.put("info", entityInfo);
7051  1143 audit.info(jsonObject.toString());
7052    }
7053   
 
7054  67 toggle public static int getPortOffset() {
7055  67 ServerConfiguration carbonConfig = ServerConfiguration.getInstance();
7056  67 String portOffset = System.getProperty(APIConstants.PORT_OFFSET_SYSTEM_VAR,
7057    carbonConfig.getFirstProperty(APIConstants.PORT_OFFSET_CONFIG));
7058  67 try {
7059  67 if ((portOffset != null)) {
7060  67 return Integer.parseInt(portOffset.trim());
7061    } else {
7062  0 return 0;
7063    }
7064    } catch (NumberFormatException e) {
7065  0 log.error("Invalid Port Offset: " + portOffset + ". Default value 0 will be used.", e);
7066  0 return 0;
7067    }
7068    }
7069   
 
7070  0 toggle public static boolean isQueryParamDataPublishingEnabled() {
7071  0 return ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService().getAPIManagerConfiguration().
7072    getThrottleProperties().isEnableQueryParamConditions();
7073    }
7074   
 
7075  0 toggle public static boolean isHeaderDataPublishingEnabled() {
7076  0 return ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService().getAPIManagerConfiguration().
7077    getThrottleProperties().isEnableHeaderConditions();
7078    }
7079   
 
7080  0 toggle public static boolean isJwtTokenPublishingEnabled() {
7081  0 return ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService().getAPIManagerConfiguration().
7082    getThrottleProperties().isEnableJwtConditions();
7083    }
7084   
 
7085  0 toggle public static String getAnalyticsServerURL() {
7086  0 return ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService().getAPIAnalyticsConfiguration().
7087    getDasServerUrl();
7088    }
7089   
 
7090  0 toggle public static String getAnalyticsServerUserName() {
7091  0 return ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService().getAPIAnalyticsConfiguration().
7092    getDasReceiverServerUser();
7093    }
7094   
 
7095  0 toggle public static String getAnalyticsServerPassword() {
7096  0 return ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService().getAPIAnalyticsConfiguration().
7097    getDasReceiverServerPassword();
7098    }
7099   
7100    /**
7101    * Create the Cache object from the given parameters
7102    *
7103    * @param cacheManagerName - Name of the Cache Manager
7104    * @param cacheName - Name of the Cache
7105    * @param modifiedExp - Value of the MODIFIED Expiry Type
7106    * @param accessExp - Value of the ACCESSED Expiry Type
7107    * @return - The cache object
7108    */
 
7109  51 toggle public static Cache getCache(final String cacheManagerName, final String cacheName, final long modifiedExp,
7110    final long accessExp) {
7111   
7112  51 return Caching.getCacheManager(
7113    cacheManagerName).createCacheBuilder(cacheName).
7114    setExpiry(CacheConfiguration.ExpiryType.MODIFIED, new CacheConfiguration.Duration(TimeUnit.SECONDS,
7115    modifiedExp)).
7116    setExpiry(CacheConfiguration.ExpiryType.ACCESSED, new CacheConfiguration.Duration(TimeUnit.SECONDS,
7117    accessExp)).setStoreByValue(false).build();
7118    }
7119   
7120    /**
7121    * This method is used to get the actual endpoint password of an API from the hidden property
7122    * in the case where the handler APIEndpointPasswordRegistryHandler is enabled in registry.xml
7123    *
7124    * @param api The API
7125    * @param registry The registry object
7126    * @return The actual password of the endpoint if exists
7127    * @throws RegistryException Throws if the api resource doesn't exist
7128    */
 
7129  0 toggle private static String getActualEpPswdFromHiddenProperty(API api, Registry registry) throws RegistryException {
7130  0 String apiPath = APIUtil.getAPIPath(api.getId());
7131  0 Resource apiResource = registry.get(apiPath);
7132  0 return apiResource.getProperty(APIConstants.REGISTRY_HIDDEN_ENDPOINT_PROPERTY);
7133    }
7134   
7135    /**
7136    * To check whether given role exist in the array of roles.
7137    *
7138    * @param userRoleList Role list to check against.
7139    * @param accessControlRole Access Control Role.
7140    * @return true if the Array contains the role specified.
7141    */
 
7142  12 toggle public static boolean compareRoleList(String[] userRoleList, String accessControlRole) {
7143  12 if (userRoleList != null) {
7144  12 for (String userRole : userRoleList) {
7145  24 if (userRole.equalsIgnoreCase(accessControlRole)) {
7146  8 return true;
7147    }
7148    }
7149    }
7150  4 return false;
7151    }
7152   
7153    /**
7154    * To clear the publisherRoleCache for certain users.
7155    *
7156    * @param userName Names of the user.
7157    */
 
7158  35 toggle public static void clearRoleCache(String userName) {
7159  35 if (isPublisherRoleCacheEnabled) {
7160  35 Caching.getCacheManager(APIConstants.API_MANAGER_CACHE_MANAGER).getCache(APIConstants
7161    .API_PUBLISHER_ADMIN_PERMISSION_CACHE).remove(userName);
7162  35 Caching.getCacheManager(APIConstants.API_MANAGER_CACHE_MANAGER).getCache(APIConstants
7163    .API_USER_ROLE_CACHE).remove(userName);
7164    }
7165    }
7166   
7167    /**
7168    * Used in application sharing to check if this featuer is enabled
7169    *
7170    * @return returns true if ENABLE_MULTIPLE_GROUPID is set to True
7171    */
 
7172  313 toggle public static boolean isMultiGroupAppSharingEnabled() {
7173   
7174  313 if (multiGrpAppSharing == null) {
7175   
7176  18 APIManagerConfiguration config = ServiceReferenceHolder.getInstance().
7177    getAPIManagerConfigurationService().getAPIManagerConfiguration();
7178   
7179  18 String groupIdExtractorClass = config.getFirstProperty(APIConstants
7180    .API_STORE_GROUP_EXTRACTOR_IMPLEMENTATION);
7181   
7182  18 if (groupIdExtractorClass != null && !groupIdExtractorClass.isEmpty()) {
7183  0 try {
7184   
7185  0 LoginPostExecutor groupingExtractor = (LoginPostExecutor) APIUtil.getClassForName
7186    (groupIdExtractorClass).newInstance();
7187   
7188  0 if (groupingExtractor instanceof NewPostLoginExecutor) {
7189  0 multiGrpAppSharing = "true";
7190    } else {
7191  0 multiGrpAppSharing = "false";
7192    }
7193    // if there is a exception the default flow will work hence ingnoring the applications
7194    } catch (InstantiationException e) {
7195  0 multiGrpAppSharing = "false";
7196    } catch (IllegalAccessException e) {
7197  0 multiGrpAppSharing = "false";
7198    } catch (ClassNotFoundException e) {
7199  0 multiGrpAppSharing = "false";
7200    }
7201    } else {
7202  18 multiGrpAppSharing = "false";
7203    }
7204    }
7205  313 return Boolean.valueOf(multiGrpAppSharing);
7206    }
7207   
7208    /**
7209    * Used to reconstruct the input search query as sub context and doc content doesn't support AND search
7210    *
7211    * @param query Input search query
7212    * @return Reconstructed new search query
7213    * @throws APIManagementException If there is an error in the search query
7214    */
 
7215  6 toggle public static String constructNewSearchQuery(String query) throws APIManagementException {
7216  6 String newSearchQuery = "";
7217  6 String inputSearchQuery = query.trim();
7218   
7219    // sub context and doc content doesn't support AND search
7220  6 if (inputSearchQuery != null && inputSearchQuery.contains(" ") && !inputSearchQuery
7221    .contains(APIConstants.TAG_SEARCH_TYPE_PREFIX4)) {
7222  0 if (inputSearchQuery.split(" ").length > 1) {
7223  0 String[] searchCriterias = inputSearchQuery.split(" ");
7224  0 for (int i = 0; i < searchCriterias.length; i++) {
7225  0 if (searchCriterias[i].contains(":") && searchCriterias[i].split(":").length > 1) {
7226  0 if (APIConstants.DOCUMENTATION_SEARCH_TYPE_PREFIX
7227    .equalsIgnoreCase(searchCriterias[i].split(":")[0])
7228    || APIConstants.SUBCONTEXT_SEARCH_TYPE_PREFIX
7229    .equalsIgnoreCase(searchCriterias[i].split(":")[0])) {
7230  0 throw new APIManagementException("Invalid query. AND based search is not supported for "
7231    + "doc and subcontext prefixes");
7232    }
7233    }
7234  0 if (i == 0) {
7235  0 newSearchQuery = APIUtil.getSingleSearchCriteria(searchCriterias[i]);
7236    } else {
7237  0 newSearchQuery = newSearchQuery + APIConstants.SEARCH_AND_TAG + APIUtil
7238    .getSingleSearchCriteria(searchCriterias[i]);
7239    }
7240    }
7241    }
7242    } else {
7243  6 newSearchQuery = APIUtil.getSingleSearchCriteria(inputSearchQuery);
7244    }
7245  6 return newSearchQuery;
7246    }
7247   
7248    /**
7249    * To set the resource properties to the API.
7250    *
7251    * @param api API that need to set the resource properties.
7252    * @param registry Registry to get the resource from.
7253    * @param artifactPath Path of the API artifact.
7254    * @return Updated API.
7255    * @throws RegistryException Registry Exception.
7256    */
 
7257  2880 toggle private static API setResourceProperties(API api, Registry registry, String artifactPath) throws RegistryException {
7258  2880 Resource apiResource = registry.get(artifactPath);
7259  2880 Properties properties = apiResource.getProperties();
7260  2880 if (properties != null) {
7261  2880 Enumeration propertyNames = properties.propertyNames();
7262  41456 while (propertyNames.hasMoreElements()) {
7263  38576 String propertyName = (String) propertyNames.nextElement();
7264  38576 if (log.isDebugEnabled()) {
7265  1624 log.debug("API '" + api.getId().toString() + "' " + "has the property " + propertyName);
7266    }
7267  38576 if (propertyName.startsWith(APIConstants.API_RELATED_CUSTOM_PROPERTIES_PREFIX)) {
7268  0 api.addProperty(propertyName.substring(APIConstants.API_RELATED_CUSTOM_PROPERTIES_PREFIX.length()),
7269    apiResource.getProperty(propertyName));
7270    }
7271    }
7272    }
7273  2880 api.setAccessControl(apiResource.getProperty(APIConstants.ACCESS_CONTROL));
7274   
7275  2880 String accessControlRoles = null;
7276   
7277  2880 String displayPublisherRoles = apiResource.getProperty(APIConstants.DISPLAY_PUBLISHER_ROLES);
7278  2880 if (displayPublisherRoles == null) {
7279   
7280  0 String publisherRoles = apiResource.getProperty(APIConstants.PUBLISHER_ROLES);
7281   
7282  0 if (publisherRoles != null) {
7283  0 accessControlRoles = APIConstants.NULL_USER_ROLE_LIST.equals(
7284    apiResource.getProperty(APIConstants.PUBLISHER_ROLES)) ?
7285    null : apiResource.getProperty(APIConstants.PUBLISHER_ROLES);
7286    }
7287    } else {
7288  2880 accessControlRoles = APIConstants.NULL_USER_ROLE_LIST.equals(displayPublisherRoles) ?
7289    null : displayPublisherRoles;
7290    }
7291   
7292  2880 api.setAccessControlRoles(accessControlRoles);
7293  2880 return api;
7294    }
7295   
7296    /**
7297    * This method is used to get the authorization configurations from the tenant registry or from api-manager.xml if
7298    * config is not available in tenant registry
7299    *
7300    * @param tenantId The Tenant ID
7301    * @param property The configuration to get from tenant registry or api-manager.xml
7302    * @return The configuration read from tenant registry or api-manager.xml
7303    * @throws APIManagementException Throws if the registry resource doesn't exist
7304    * or the content cannot be parsed to JSON
7305    */
 
7306  492 toggle public static String getOAuthConfiguration(int tenantId, String property)
7307    throws APIManagementException {
7308  492 String authConfigValue = APIUtil
7309    .getOAuthConfigurationFromTenantRegistry(tenantId, property);
7310  492 if (StringUtils.isBlank(authConfigValue)) {
7311  492 authConfigValue = APIUtil.getOAuthConfigurationFromAPIMConfig(property);
7312    }
7313  492 return authConfigValue;
7314    }
7315   
7316    /**
7317    * This method is used to get the authorization configurations from the tenant registry
7318    *
7319    * @param tenantId The Tenant ID
7320    * @param property The configuration to get from tenant registry
7321    * @return The configuration read from tenant registry or else null
7322    * @throws APIManagementException Throws if the registry resource doesn't exist
7323    * or the content cannot be parsed to JSON
7324    */
 
7325  502 toggle public static String getOAuthConfigurationFromTenantRegistry(int tenantId, String property)
7326    throws APIManagementException {
7327  502 try {
7328  502 Registry registryConfig = ServiceReferenceHolder.getInstance().getRegistryService()
7329    .getConfigSystemRegistry(tenantId);
7330   
7331  502 if (registryConfig.resourceExists(APIConstants.API_TENANT_CONF_LOCATION)) {
7332  502 Resource resource = registryConfig.get(APIConstants.API_TENANT_CONF_LOCATION);
7333  502 String content = new String((byte[]) resource.getContent(), Charset.defaultCharset());
7334  502 if (content != null) {
7335  502 JSONObject tenantConfig = (JSONObject) new JSONParser().parse(content);
7336    //Read the configuration from the tenant registry
7337  502 String oAuthConfiguration = "";
7338  502 if (null != tenantConfig.get(property)) {
7339  0 StringBuilder stringBuilder = new StringBuilder();
7340  0 stringBuilder.append(tenantConfig.get(property));
7341  0 oAuthConfiguration = stringBuilder.toString();
7342    }
7343   
7344  502 if (!StringUtils.isBlank(oAuthConfiguration)) {
7345  0 return oAuthConfiguration;
7346    }
7347    }
7348    }
7349    } catch (RegistryException e) {
7350  0 String msg = "Error while retrieving " + property + " from tenant registry.";
7351  0 throw new APIManagementException(msg, e);
7352    } catch (ParseException pe) {
7353  0 String msg = "Couldn't create json object from Swagger object for custom OAuth header.";
7354  0 throw new APIManagementException(msg, pe);
7355    }
7356  502 return null;
7357    }
7358   
7359    /**
7360    * This method is used to get the authorization configurations from the api manager configurations
7361    *
7362    * @param property The configuration to get from api-manager.xml
7363    * @return The configuration read from api-manager.xml or else null
7364    * @throws APIManagementException Throws if the registry resource doesn't exist
7365    * or the content cannot be parsed to JSON
7366    */
 
7367  790 toggle public static String getOAuthConfigurationFromAPIMConfig(String property)
7368    throws APIManagementException {
7369   
7370    //If tenant registry doesn't have the configuration, then read it from api-manager.xml
7371  790 APIManagerConfiguration apimConfig = ServiceReferenceHolder.getInstance()
7372    .getAPIManagerConfigurationService().getAPIManagerConfiguration();
7373  790 String oAuthConfiguration = apimConfig.getFirstProperty(APIConstants.OAUTH_CONFIGS + property);
7374   
7375  790 if (!StringUtils.isBlank(oAuthConfiguration)) {
7376  15 return oAuthConfiguration;
7377    }
7378   
7379  775 return null;
7380    }
7381   
 
7382  0 toggle public static boolean isForgetPasswordConfigured() {
7383  0 AxisConfiguration axis2Config = ServiceReferenceHolder.getContextService().getServerConfigContext()
7384    .getAxisConfiguration();
7385  0 TransportOutDescription emailTransportSender = axis2Config.getTransportOut(APIConstants.EMAIL_TRANSPORT);
7386  0 if (emailTransportSender != null) {
7387  0 return true;
7388    }
7389  0 return false;
7390    }
7391   
7392    /**
7393    * Used to get the custom pagination limit for store
7394    *
7395    * @return returns the store pagination value from api-manager.xml
7396    */
 
7397  4 toggle public static int getApisPerPageInStore() {
7398  4 String paginationLimit = ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService()
7399    .getAPIManagerConfiguration().getFirstProperty(APIConstants.API_STORE_APIS_PER_PAGE);
7400  4 if (paginationLimit != null) {
7401  0 return Integer.parseInt(paginationLimit);
7402    }
7403  4 return 0;
7404    }
7405   
7406    /**
7407    * Used to get the custom pagination limit for publisher
7408    *
7409    * @return returns the publisher pagination value from api-manager.xml
7410    */
 
7411  0 toggle public static int getApisPerPageInPublisher() {
7412  0 String paginationLimit = ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService()
7413    .getAPIManagerConfiguration().getFirstProperty(APIConstants.API_PUBLISHER_APIS_PER_PAGE);
7414  0 if (paginationLimit != null) {
7415  0 return Integer.parseInt(paginationLimit);
7416    }
7417  0 return 0;
7418    }
7419   
7420   
7421    /**
7422    * This method is used to get application from client id.
7423    *
7424    * @param clientId client id
7425    * @return application object.
7426    * @throws APIManagementException
7427    */
 
7428  399 toggle public static Application getApplicationByClientId(String clientId) throws APIManagementException {
7429  399 ApiMgtDAO apiMgtDAO = ApiMgtDAO.getInstance();
7430  399 return apiMgtDAO.getApplicationByClientId(clientId);
7431    }
7432   
 
7433  8 toggle public static List<ConditionDto> extractConditionDto(String base64EncodedString) throws ParseException {
7434   
7435  8 List<ConditionDto> conditionDtoList = new ArrayList<>();
7436  8 String base64Decoded = new String(Base64.decodeBase64(base64EncodedString));
7437  8 JSONArray conditionJsonArray = (JSONArray) new JSONParser().parse(base64Decoded);
7438  8 for (Object conditionJson : conditionJsonArray) {
7439  0 ConditionDto conditionDto = new ConditionDto();
7440  0 JSONObject conditionJsonObject = (JSONObject) conditionJson;
7441  0 if (conditionJsonObject.containsKey(PolicyConstants.IP_SPECIFIC_TYPE.toLowerCase())) {
7442  0 JSONObject ipSpecificCondition = (JSONObject) conditionJsonObject.get(PolicyConstants.IP_SPECIFIC_TYPE
7443    .toLowerCase());
7444  0 ConditionDto.IPCondition ipCondition = new Gson().fromJson(ipSpecificCondition.toJSONString(),
7445    ConditionDto.IPCondition.class);
7446  0 conditionDto.setIpCondition(ipCondition);
7447  0 } else if (conditionJsonObject.containsKey(PolicyConstants.IP_RANGE_TYPE.toLowerCase())) {
7448  0 JSONObject ipRangeCondition = (JSONObject) conditionJsonObject.get(PolicyConstants.IP_RANGE_TYPE
7449    .toLowerCase());
7450  0 ConditionDto.IPCondition ipCondition = new Gson().fromJson(ipRangeCondition.toJSONString(),
7451    ConditionDto.IPCondition.class);
7452  0 conditionDto.setIpRangeCondition(ipCondition);
7453    }
7454  0 if (conditionJsonObject.containsKey(PolicyConstants.JWT_CLAIMS_TYPE.toLowerCase())) {
7455  0 JSONObject jwtClaimConditions = (JSONObject) conditionJsonObject.get(PolicyConstants.JWT_CLAIMS_TYPE
7456    .toLowerCase());
7457  0 ConditionDto.JWTClaimConditions jwtClaimCondition = new Gson().fromJson(jwtClaimConditions
7458    .toJSONString(), ConditionDto.JWTClaimConditions.class);
7459  0 conditionDto.setJwtClaimConditions(jwtClaimCondition);
7460    }
7461  0 if (conditionJsonObject.containsKey(PolicyConstants.HEADER_TYPE.toLowerCase())) {
7462  0 JSONObject headerConditionJson = (JSONObject) conditionJsonObject.get(PolicyConstants.HEADER_TYPE
7463    .toLowerCase());
7464  0 ConditionDto.HeaderConditions headerConditions = new Gson().fromJson(headerConditionJson
7465    .toJSONString(), ConditionDto.HeaderConditions.class);
7466  0 conditionDto.setHeaderConditions(headerConditions);
7467    }
7468   
7469  0 if (conditionJsonObject.containsKey(PolicyConstants.QUERY_PARAMETER_TYPE.toLowerCase())) {
7470  0 JSONObject queryParamConditionJson = (JSONObject) conditionJsonObject.get(PolicyConstants
7471    .QUERY_PARAMETER_TYPE.toLowerCase());
7472  0 ConditionDto.QueryParamConditions queryParamCondition = new Gson().fromJson(queryParamConditionJson
7473    .toJSONString(), ConditionDto.QueryParamConditions.class);
7474  0 conditionDto.setQueryParameterConditions(queryParamCondition);
7475    }
7476  0 conditionDtoList.add(conditionDto);
7477    }
7478  8 conditionDtoList.sort(new Comparator<ConditionDto>() {
 
7479  0 toggle @Override
7480    public int compare(ConditionDto o1, ConditionDto o2) {
7481   
7482  0 if (o1.getIpCondition() != null && o2.getIpCondition() == null) {
7483  0 return -1;
7484  0 } else if (o1.getIpCondition() == null && o2.getIpCondition() != null) {
7485  0 return 1;
7486    } else {
7487  0 if (o1.getIpRangeCondition() != null && o2.getIpRangeCondition() == null) {
7488  0 return -1;
7489  0 } else if (o1.getIpRangeCondition() == null && o2.getIpRangeCondition() != null) {
7490  0 return 1;
7491    } else {
7492  0 if (o1.getHeaderConditions() != null && o2.getHeaderConditions() == null) {
7493  0 return -1;
7494  0 } else if (o1.getHeaderConditions() == null && o2.getHeaderConditions() != null) {
7495  0 return 1;
7496    } else {
7497  0 if (o1.getQueryParameterConditions() != null && o2.getQueryParameterConditions() == null) {
7498  0 return -1;
7499  0 } else if (o1.getQueryParameterConditions() == null && o2.getQueryParameterConditions()
7500    != null) {
7501  0 return 1;
7502    } else {
7503  0 if (o1.getJwtClaimConditions() != null && o2.getJwtClaimConditions() == null) {
7504  0 return -1;
7505  0 } else if (o1.getJwtClaimConditions() == null && o2.getJwtClaimConditions() != null) {
7506  0 return 1;
7507    }
7508    }
7509    }
7510    }
7511    }
7512  0 return 0;
7513    }
7514    });
7515   
7516  8 return conditionDtoList;
7517    }
7518   
7519    /**
7520    * Get if there any tenant-specific application configurations from the tenant
7521    * registry
7522    *
7523    * @param tenantId The Tenant Id
7524    * @return JSONObject The Application Attributes read from tenant registry or else null
7525    * @throws APIManagementException Throws if the registry resource doesn't exist
7526    * or the content cannot be parsed to JSON
7527    */
 
7528  156 toggle public static JSONObject getAppAttributeKeysFromRegistry(int tenantId) throws APIManagementException {
7529   
7530  156 try {
7531  156 Registry registryConfig = ServiceReferenceHolder.getInstance().getRegistryService().getConfigSystemRegistry(tenantId);
7532  156 if (registryConfig.resourceExists(APIConstants.API_TENANT_CONF_LOCATION)) {
7533  156 Resource resource = registryConfig.get(APIConstants.API_TENANT_CONF_LOCATION);
7534  156 String content = new String((byte[]) resource.getContent(), Charset.defaultCharset());
7535  156 if (content != null) {
7536  156 JSONObject tenantConfigs = (JSONObject) new JSONParser().parse(content);
7537  156 String property = APIConstants.ApplicationAttributes.APPLICATION_CONFIGURATIONS;
7538  156 if (tenantConfigs.keySet().contains(property)) {
7539  0 return (JSONObject) tenantConfigs.get(APIConstants.ApplicationAttributes.APPLICATION_CONFIGURATIONS);
7540    }
7541    }
7542    }
7543    } catch (RegistryException exception) {
7544  0 String msg = "Error while retrieving application attributes from tenant registry.";
7545  0 throw new APIManagementException(msg, exception);
7546    } catch (ParseException parseExceptione) {
7547  0 String msg = "Couldn't create json object from Swagger object for custom application attributes.";
7548  0 throw new APIManagementException(msg, parseExceptione);
7549    }
7550  156 return null;
7551    }
7552   
7553    /**
7554    * Validate the input file name for invalid path elements
7555    *
7556    * @param fileName
7557    */
 
7558  0 toggle public static void validateFileName(String fileName) throws APIManagementException {
7559  0 if (!fileName.isEmpty() && (fileName.contains("../") || fileName.contains("..\\"))) {
7560  0 handleException("File name contains invalid path elements. " + fileName);
7561    }
7562    }
7563   
7564    /**
7565    * Convert special characters to encoded value.
7566    *
7567    * @param role
7568    * @return encorded value
7569    */
 
7570  10 toggle public static String sanitizeUserRole(String role) {
7571  10 if (role.contains("&")) {
7572  0 return role.replaceAll("&", "%26");
7573    } else {
7574  10 return role;
7575    }
7576    }
7577   
7578    /**
7579    * Util method to call SP rest api to invoke queries.
7580    *
7581    * @param appName SP app name that the query should run against
7582    * @param query query
7583    * @return jsonObj JSONObject of the response
7584    * @throws APIManagementException
7585    */
 
7586  0 toggle public static JSONObject executeQueryOnStreamProcessor(String appName, String query) throws APIManagementException {
7587  0 String spEndpoint = APIManagerAnalyticsConfiguration.getInstance().getDasServerUrl() + "/stores/query";
7588  0 String spUserName = APIManagerAnalyticsConfiguration.getInstance().getDasServerUser();
7589  0 String spPassword = APIManagerAnalyticsConfiguration.getInstance().getDasServerPassword();
7590  0 byte[] encodedAuth = Base64
7591    .encodeBase64((spUserName + ":" + spPassword).getBytes(Charset.forName("ISO-8859-1")));
7592  0 String authHeader = "Basic " + new String(encodedAuth);
7593  0 URL spURL;
7594  0 try {
7595  0 spURL = new URL(spEndpoint);
7596   
7597  0 HttpClient httpClient = APIUtil.getHttpClient(spURL.getPort(), spURL.getProtocol());
7598  0 HttpPost httpPost = new HttpPost(spEndpoint);
7599   
7600  0 httpPost.setHeader(HttpHeaders.AUTHORIZATION, authHeader);
7601  0 JSONObject obj = new JSONObject();
7602  0 obj.put("appName", appName);
7603  0 obj.put("query", query);
7604   
7605  0 if (log.isDebugEnabled()) {
7606  0 log.debug("Request from SP: " + obj.toJSONString());
7607    }
7608   
7609  0 StringEntity requestEntity = new StringEntity(obj.toJSONString(), ContentType.APPLICATION_JSON);
7610   
7611  0 httpPost.setEntity(requestEntity);
7612   
7613  0 HttpResponse response;
7614  0 try {
7615  0 response = httpClient.execute(httpPost);
7616  0 HttpEntity entity = response.getEntity();
7617  0 if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
7618  0 String error = "Error while invoking SP rest api : " + response.getStatusLine().getStatusCode()
7619    + " " + response.getStatusLine().getReasonPhrase();
7620  0 log.error(error);
7621  0 throw new APIManagementException(error);
7622    }
7623  0 String responseStr = EntityUtils.toString(entity);
7624  0 if (log.isDebugEnabled()) {
7625  0 log.debug("Response from SP: " + responseStr);
7626    }
7627  0 JSONParser parser = new JSONParser();
7628  0 return (JSONObject) parser.parse(responseStr);
7629   
7630    } catch (ClientProtocolException e) {
7631  0 handleException("Error while connecting to the server ", e);
7632    } catch (IOException e) {
7633  0 handleException("Error while connecting to the server ", e);
7634    } catch (ParseException e) {
7635  0 handleException("Error while parsing the response ", e);
7636    } finally {
7637  0 httpPost.reset();
7638    }
7639   
7640    } catch (MalformedURLException e) {
7641  0 handleException("Error while parsing the stream processor url", e);
7642    }
7643   
7644  0 return null;
7645   
7646    }
7647   
7648   
7649    }